Reputation: 388
I'm looking for a way to check a string that a user inputs when prompted (let's take it to be a string variable "userinput") from an array of 10 other strings. So far I have:
while (userinput.empty()) //Check for empty input
{
cout << "Please enter your identity.\n"; //Identify user
getline(cin, userinput);
do //Check to see if user is the same as the string variable "user"
{
cout << "This user is either non existent or has access privileges revoked.\n"; //Wrong username!
cout << "Please re-enter the username.\n";
getline(cin, userinput);
}
while (user != userinput);
}
It can be seen though, that this only works for a single string variable "user". How would I change this for a string array?
The array itself is the following:
string arr[10] = {"Test1", "Test2", "Test3", "Test4", "Test5", "Test6", "Test7", "Test8", "Test9", "Test10"};
Please note: I'm not intending to use passwords, only usernames.
Upvotes: 0
Views: 365
Reputation: 2984
You can use the built-in count
function like so:
do{
getline(cin, userinput);
}
while(!std::count(arr, arr+10, userinput));
On ideone as well.
This is how your loop should look:
cout << "Please enter your identity.\n"; //Identify user
getline(cin, userinput);
while (!std::count(arr, arr+10, userinput)) //Check to see if user is the same as the string variable "user"
{
cout << "This user is either non existent or has access privileges revoked.\n"; //Wrong username!
cout << "Please re-enter the username.\n";
getline(cin, userinput);
}
You can see it here.
Upvotes: 3
Reputation: 942
If you have a big number of strings to compare, then it will be much more efficiently to use a hash map (std::unordered_set
) instead of an array. Search in a hash table is much faster then in an array.
unordered_set<string> valid_inputs {"Test1", "Test2", "Test3", "Test4", "Test5", "Test6"};
Then you can check an user input in such a way:
if (valid_inputs.find(user_input) == valid_inputs.end())
cout << "error";
else
cout << "success";
Upvotes: 1
Reputation: 1
Put the check in a separate function
bool isValidUserName(const string& input) {
for(int i = 0; i < 10; ++i) {
if(input == arr[i]) {
return true;
}
}
return false;
}
and use it as condition in the while
while (!isValidUserName(userinput));
Upvotes: 2