简体   繁体   English

如何限制用户仅在C ++中输入单个字符

[英]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. 我是一个初学者,我试图限制用户仅输入一个字符,我知道使用cin.get(char) ,它只会从输入中读取一个字符,但我不希望另一个字符保留在缓冲区中。 Here is a sample of my code using EOF, but it doesn't seem to work. 这是我使用EOF的代码示例,但似乎不起作用。

     #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. 我已经将此用于数字输入,并且eof可以正常工作。 But for the char category the str.eof() seems to be false. 但是对于char categorystr.eof()似乎是错误的。 Can someone explain? 有人可以解释吗? Thanks in advance. 提前致谢。

The eof flag is only set if you read try to read past the end of the stream. 如果你读尝试读取超过了流的末尾EOF标志时,才设置。 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()) . 如果str >> category在流的末尾读取, if (str >> category)评估结果为false且未进入测试循环(str.eof()) If there was one character on the line you would have to attempt to read two characters to trigger eof. 如果一行上只有一个字符,则您将不得不尝试读取两个字符以触发eof。 Reading two characters is far more effort than testing the length of line to see how long it is. 读两个字符是不是测试的长度远远更多的精力line ,看看它有多长。

while (getline (cin, line)) got the whole line from the console. while (getline (cin, line))从控制台获取了整行。 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 . 如果您不在stringstream它,那没关系,当您在while循环时, cin消失了。

In fact, the stringstream isn't doing you any favours. 实际上, stringstream对您没有任何帮助。 Once you've confirmed the length of the line that was read, you can just use line[0] . 确认已读取的行的长度后,您只需使用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";
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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