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

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

提问人:John Deveraux 提问时间:10/23/2017 更新时间:10/23/2017 访问量:2380

问:

我是初学者,我试图将用户限制为仅输入单个字符,我确实知道使用并且它只会从输入中读取一个字符,但我不希望其他字符留在缓冲区中。这是我使用 EOF 的代码示例,但它似乎不起作用。cin.get(char)

     #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";
         }                  
     }

我已将其用于数字输入,并且 eof 工作正常。 但对于似乎是错误的。 有人可以解释一下吗?提前致谢。char categorystr.eof()

C++ 字符串 字符 eof StringStream

评论


答:

0赞 user4581301 10/23/2017 #1

仅当您读取尝试读取的末尾时,才会设置 eof 标志。如果读取超过流的末尾,则计算结果为 false,并且不会进入循环进行测试。如果行上有一个字符,则必须尝试读取两个字符才能触发 eof。阅读两个字符比测试它的长度要费力得多。str >> categoryif (str >> category)(str.eof())line

while (getline (cin, line))从控制台获取了整条线。如果你不消耗它,没关系,当你在 .stringstreamcinwhile

事实上,这对你没有任何好处。确认已读取行的长度后,只需使用 .stringstreamline[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";
        }
    }
}

评论

0赞 John Deveraux 10/23/2017
谢谢,这对我有很大帮助,但是你知道为什么返回的 eof 值为 0 吗?
0赞 user4581301 10/23/2017
@JohnDeveraux更新的答案来解释为什么不起作用。eof()