简体   繁体   中英

c++ validate input does not work

I am writing this code below and everything is working fine except when I type multiple characterS it suppose to give invalid input without exit the program but what is happen that when I wrote multiple characters starting quite 'Q' or 'q' it is exit the program and I do not want that I only want to exit if I type 'q' or 'Q'

int main()
{
    char grade;

    while(grade!='Q'&& grade!='q') {

        cout<<"\nEnter one grade Letter from the following"
            <<" (A ,B,C,D or F) or Please or 'q' to quite: ";

        cin>>grade;
        if (cin.get() != '\n') // Look at the next character
            {

                cin.ignore(1000, '\n'); // Clear the input stream

                cout << "\nInvalid input !\n";
            }

        else if (grade != 'A' && grade != 'a'
                 &&  grade != 'B' && grade != 'b'
                 &&  grade != 'C' && grade != 'c'
                 &&  grade != 'D' && grade != 'd'
                 &&  grade != 'F' && grade != 'f'
                 &&  grade != 'Q' && grade != 'q'
                 ) {

            cout << "\nInvalid input !\n";

        }

        else if(grade =='A'||grade=='a')
            cout<<"Excellent"<<endl;
        else if(grade=='B'|| grade=='b')
            cout<<"Good"<<endl;
        else if(grade=='C' || grade=='c')
            cout<<"Fair"<<endl;
        else if (grade=='D' || grade=='d')
            cout<<"Poor"<<endl;
        else if (grade=='F' || grade=='f')
            cout<<"Failure"<<endl;
        //else

    }

    return 0;
}

If you do not want to take into consideration only the first character that's entered, then don't read a single character and then base all the decisions on it. Use std::getline() to read an entire line into a std::string , and then check it for valid values.

Additionally, your existing code has undefined behavior, because grade is uninitialized before its first use.

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