Search code examples
c++stringif-statementdo-whilepassword-checker

Ask name, if wrong ask again, if right, keep going ( Not working ) C++


That's my code. What i'm trying to do here is a code that Asks for a name ( like a pass ) if the name is wrong, then the program says those 3 error messages and asks the name again, until one of the 2 white-listed names is given, then just keep going with the code.

int main(void)
{
setlocale(LC_ALL, "Portuguese");
string Name = "";
cout << "Whats your name dude ?" << endl;
cin >> Name;

if (Name == "ighor" ||
    Name == "indio")
    {
    cout << "Welcome friend =D" << endl;
    system("pause");
    system("cls");
    }
    else
    {
        do  
        {
            cout << "Sorry, wrong name =[" << endl;
            system("pause");
            system("cls");
            cout << "I'll give you another chance =]" << endl;
            system("pause");
            system("cls");
            cout << "Write your name again" << endl;
            cin >> Name;

            if (Name == "ighor" ||
                Name == "indio")
            {
                continue;
            }

        }   while (Name != "ighor" ||
                   Name != "indio");


    }

cout << "Whats up" << Name << endl;
system("pause");
system("cls");      
        return 0;

}

My tests with this code gave me this :
If i put a white-listed name ( indio or ighor ) i get the massage of correct name

"Welcome friend =]".

If i put a wrong name, i get the massage of wrong name, nice, then i'm asked to enter the name again, i put one of the white-listed names and it keeps saying that it's the wrong name, wrong names also show wrong name message.


Solution

  • The logic in the do-while loop is flawed. Instead of

                continue;
    

    you need

                break;
    

    continue; continues with the next iteration of the loop. break; breaks the loop.

    Also, the while statement logic incorrect. You need to use:

    while (Name != "ighor" &&  Name != "indio");
                          ^^^ not ||
    

    Having said that, you only need one of the checks, not both.

    You can use:

    do  
    {
       ...
    
       if (Name == "ighor" || Name == "indio")
       {
          break;
       }
    
    } while (true);
    

    or

    do  
    {
       ...
    
    }  while (Name != "ighor" && Name != "indio");