简体   繁体   中英

C++ validate user input is a single character

optionTest is a string, and option is a char. The issue occurs when I enter something like "ee e". The last "e" is grabbed despite my ignore/clear. I want the validation loop to run as long as the input is not a single character.

    cin >> optionTest;

    while (optionTest.length() != 1) {
        cout << "Invalid input. please try again." << endl;
        cin.ignore();
        cin.clear();
        //receive option
        cin >> optionTest;
    }

    option = optionTest[0];

From std::basic_istream::ignore() 's description :

basic_istream& ignore( std::streamsize count = 1, int_type delim = Traits::eof() );

it extracts characters from the stream and discards them until any one of the following conditions occurs:

count characters were extracted. This test is disabled in the special case when count equals std::numeric_limits<std::streamsize>::max()

Since you call it with empty parentheses, count is 1 and thus only one character is extracted (space character, in your case).

Try cin.ignore(std::numeric_limits<std::streamsize>::max()) (or at least any number sufficiently large).

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