[英]C++ (Linear Search and Sorting)
Help with C++. 有关C ++的帮助。 Two things that I am struggling with 我正在努力的两件事
I am trying to do a linear search of name of list but for some reason the message "ABSENT!" 我试图对列表名称进行线性搜索,但由于某种原因出现消息“ ABSENT!”。 will not come up when I type in the wrong name. 输入错误名称时不会出现。 How do I fix that? 我该如何解决?
I am trying to sort the entered name alphabetically in ascending order by their last name but I don't really know how to use that for loop and array for that. 我试图按输入名称的姓氏的升序对字母进行排序,但是我真的不知道如何将其用于循环和数组。
Below is what I have for coding so far (Where it says Linear Search and Sorting is where I need help and that needs to be revised). 以下是到目前为止我要进行编码的内容(上面所说的“线性搜索和排序”是我需要帮助的地方,需要进行修改)。
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
const int Students = 10;
int numStudents = 0;
string StudentName[Students];
int found = -1;
string SearchName;
int main() {
cout << "Enter the number of students (1-10): ";
cin >> numStudents;
for (int i = 0; i < numStudents; i++) {
cout << "Enter a name: ";
cin.ignore();
getline(cin, StudentName[i]);
}
cout << "\nEnter a search name: ";
cin.ignore();
getline(cin, SearchName);
**//Linear Search
for (int i = 0; i < numStudents; i++) {
if (StudentName[i] == SearchName)
found = i;
cout << "PRESENT! Found in position " << found << endl;
if (StudentName[i] != SearchName)
found = 0;
cout << "ABSENT!" << endl;
}
//Sorting
for (int i = 0; i < numStudents - 1; i++) {
for (int j = i + 1; j < numStudents; j++)
if (StudentName[i] > StudentName[j]) {
string t = StudentName[i];
StudentName[i] = StudentName[j];
StudentName[j] = t;
}
}
cout << "\nThe Sorted list is:" << "\n";**
system("pause");
return 0;
}
This code 这段代码
if (StudentName[i] == SearchName)
found = i;
cout << "PRESENT! Found in position " << found << endl;
if (StudentName[i] != SearchName)
found = 0;
cout << "ABSENT!" << endl;
is missing braces for the if statements. if语句缺少花括号。 It should be 它应该是
if (StudentName[i] == SearchName) {
found = i;
cout << "PRESENT! Found in position " << found << endl;
}
if (StudentName[i] != SearchName) {
found = 0;
cout << "ABSENT!" << endl;
}
However the code is still not right because you cannot know that you haven't found a name until you have checked all the names. 但是,代码仍然不正确,因为在检查所有名称之前,您不知道自己没有找到名称。 So logically the test for 'not found' can only go after the for loop. 因此,从逻辑上讲,“未找到”的测试只能在for循环之后进行。
I would write the code something like this 我会写这样的代码
//Linear Search
found = -1;
for (int i = 0; i < numStudents; i++) {
if (StudentName[i] == SearchName) {
found = i;
break; // we've found it, quit the loop
}
}
if (found == -1) // did we find it?
cout << "ABSENT!" << endl;
else
cout << "PRESENT! Found in position " << found << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.