1

I'm fairly new to programming, and I'm wondering if there's any way I can compare a string input to an array element? I tried the code below, and I know it's wrong, I just don't know how else to go about this.

#include <iostream> using namespace std; int main() { string Username[10] = {"name1", "name2", "name3", "name4", "name5", "name6", "name7", "name8", "name9", "name10"}; string login; int i; cout << "Enter username login: "; getline(cin, login); cout << "\n"; for (i = 0; i < 10; i++) if (login == Username[i]) { cout << "Loading user settings..."; } else cout << "Error: Wrong username entered. "; return 0; } 
1

4 Answers 4

2

You can avoid the loop and use the std::find algorithm function.

 #include <algorithm> //... bool exists = (std::find(std::begin(Username), std::end(Username), login) != std::end(Username)); 
Sign up to request clarification or add additional context in comments.

1 Comment

Oof, I was behind by 20 seconds :(
2

You should use an algorithm, like this:

if (std::find(Username, Username + 10, login) != (Username + 10)) cout << "Loading user settings..."; else cout << "Error: Wrong username entered. "; 

Comments

1

I imagine what you want to see is "Loading user settings..." if there is a match, and "Error: Wrong username entered. " if there is no match. Your if-statement should look like this:

if (login == Username[i]){ cout << "Loading user settings..."; break; } 

and your else-statement should be an else-if in the form of:

else if(i==9) cout << "Error: Wrong username entered. "; 

Two things:

1) break functions in a way such that, when the program sees a break, it ends the loop that it is currently using. When you find a match, you don't have to look any farther in the array, so break out of it.

2) You only want to print error if you have looked through the entire array, and that will only happen after you have checked the last element which, in this case, is at index 9. Changing the else to an else-if lets you specify this condition.

1 Comment

@anastaciu has a better answer, however, with respect to runtime. Although it's negligible in this case, checking else if (i==9) is a redundant step that can be avoided altogether at the cost of a bool flag.
1

You can use a bool flag to check if the user exists or not:

Running sample

//... bool exists = false; //... for (i = 0; i < 10; i++) if (login == Username[i]) { exists = true; break; } exists ? std::cout << "Loading user settings..." : std::cout << "Error: Wrong username entered. "; //... 

On a side note, see Why is "using namespace std;" considered bad practice?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.