I have put the linear search algorithm with array of structure. In the program, I have entered to 2 usernames. I tried testing the login function with the first username with index 0 and it did not show the error and displayed the right index. The second username with index 1 displays error and displays index 0, the wrong index. What did I do wrong here?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void login(InventoryRecord list[], int size) {
int i = 0;
string userMatch;
for (i = 0; i < MAX_SIZE; i++) {
cout << "\nEnter username: ";
cin >> userMatch;
if (list[i].username == userMatch) {
cout << "at index " << i << endl;
break;
}
elseif (list[i].username != userMatch) {
cout << "at index " << i << endl;
cout << "\nInvalid username! " << endl;
break;
}
}
}
You are trying to do too much inside the loop. You probably want to enter the username before the loop, and you probably want to output if the username is valid or not after the loop. The loop should only search the array so that you can know if (and where?) the username was found after the loop.
Also, when looping shouldn't you be using size instead of MAX_SIZE?