简体   繁体   中英

How do I limit user to input a single character only in C++

I am a beginner and I'm trying to limit the user to input a single character only, I do aware of using cin.get(char) and it will only read one character from the input, but I don't want the other characters be left in buffer. Here is a sample of my code using EOF, but it doesn't seem to work.

     #include <iostream>
     #include <sstream>
     using namespace std;

     string line;
     char category;
     int main()
     {
         while (getline (cin, line))
         {
             if (line.size() == 1)
             {
                 stringstream str(line);
                 if (str >> category)
                 {
                     if (str.eof())
                         break;
                 }
             }
             cout << "Please enter single character only\n";
         }                  
     }

I have used this for digit inputs and the eof works fine. But for the char category the str.eof() seems to be false. Can someone explain? Thanks in advance.

The eof flag is only set if you read try to read past the end of the stream. If str >> category read past the end of the stream, if (str >> category) would have evaluated false and not entered the loop to test (str.eof()) . If there was one character on the line you would have to attempt to read two characters to trigger eof. Reading two characters is far more effort than testing the length of line to see how long it is.

while (getline (cin, line)) got the whole line from the console. If you don't consume it in the stringstream it doesn't matter, that stuff is gone is gone from cin when you loop back around in the while .

In fact, the stringstream isn't doing you any favours. Once you've confirmed the length of the line that was read, you can just use line[0] .

#include <iostream>
using namespace std;

int main()
{
    string line; // no point to these being global.
    char category;
    while (getline(cin, line))
    {
        if (line.size() == 1)
        {
            //do stuff with line[0];
        }
        else // need to put the fail case in an else or it runs every time. 
             // Not very helpful, an error message that prints when the error 
             // didn't happen.
        {
            cout << "Please enter single character only\n";
        }
    }
}

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