简体   繁体   中英

Unable to check for similar string input C++

I'm having problems checking for similar string input from the user and i'm pretty sure i'm not getting my concepts wrong. I'm afraid i might be missing out something.

I'm trying to ensure that the user input only grade AF therefore i tried doing the input check like shown below but it doesn't seem to be working correctly.

string grade;
bool input=false;

while (!input)
{
    cout << "Please enter grade : ";
    getline(cin, grade);

    if (grade == "Grade A" || grade == "Grade B" || grade == "Grade C" || grade == "Grade D" || grade == "Grade E" || grade == "Grade F")
    {
        input = true;
        cout << "Successful input " << endl;
    }
    else
    {
        cout << "Please enter the correct input" << endl << endl;
        input = false;
    }       

}

For example if i type Grade A, it's suppose to return successful input while exiting out of the loop however it doesn't seem to work. I'm currently using Visual Studio 2015 to program this application.

The best way to go about solving this problem is using the debugger or cout to understand where things are going wrong. My first step would be to find out what the value of grade is after using getline(). If grade does not equal what you typed in, something is obviously wrong.

Remember there is always an alternative to getline(). Instead, you could use:

 cin << grade;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM