【问题标题】:How do I limit user to input a single character only in C++如何限制用户仅在 C++ 中输入单个字符
【发布时间】:2017-10-23 05:10:50
【问题描述】:

我是一个初学者,我试图限制用户只能输入一个字符,我知道使用 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 only\n";
         }                  
     }

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

【问题讨论】:

    标签: c++ string char eof stringstream


    【解决方案1】:

    eof 标志仅在您读取尝试读取流的末尾过去 时设置。如果str &gt;&gt; category 读到流的末尾,if (str &gt;&gt; category) 将评估为 false 并且不会进入循环以测试 (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 only\n";
            }
        }
    }
    

    【讨论】:

    • 谢谢,对我帮助很大,但是你知道为什么返回的eof值为0吗?
    • @JohnDeveraux 更新了答案以解释为什么 eof() 不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2017-09-12
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 2022-10-19
    • 2019-05-14
    相关资源
    最近更新 更多