0

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;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
jay
  • 1
  • 1

4 Answers4

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));
PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
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?

anastaciu
  • 23,467
  • 7
  • 28
  • 53
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.

Matt Fenlon
  • 598
  • 1
  • 6
  • 15
  • @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. – Matt Fenlon Apr 14 '20 at 21:17
1

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. ";
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
cigien
  • 57,834
  • 11
  • 73
  • 112