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

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

本文关键字:输入 单个 字符 C++ 何限制 用户      更新时间:2023-10-16

我是初学者,我试图限制用户只输入一个字符,我知道使用cin.get(char),它只会从输入中读取一个字符,但我不希望其他字符留在缓冲区中。这是我使用 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 onlyn";
         }                  
     }

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

仅当您

读取尝试读取流末尾时,才会设置 eof 标志。如果str >> category读取超过流的末尾,if (str >> category)将评估为假,并且不会进入循环以测试(str.eof())。如果行上有一个字符,则必须尝试读取两个字符才能触发 eof。阅读两个字符比测试line的长度以查看它有多长要费力得多。

while (getline (cin, line))从控制台上得到了整条线。如果你不stringstream消费它,没关系,当你在while中循环回来时,那些东西就消失了cin

事实上,stringstream并没有给你带来任何好处。确认读取的行的长度后,您可以使用 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 onlyn";
        }
    }
}