Reputation: 9
Help with 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!" 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;
}
Upvotes: 1
Views: 326
Reputation: 87957
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. 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.
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;
Upvotes: 4