jay
jay

Reputation: 11

How to check if a string matches an array element?

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;
}

Upvotes: 1

Views: 1666

Answers (4)

anastaciu
anastaciu

Reputation: 23802

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?

Upvotes: 1

cigien
cigien

Reputation: 60218

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. ";

Upvotes: 2

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

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));

Upvotes: 2

Matt Fenlon
Matt Fenlon

Reputation: 688

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.

Upvotes: 1

Related Questions