提问人:John Deveraux 提问时间:10/23/2017 更新时间:10/23/2017 访问量:2380
如何限制用户仅在 C++ 中输入单个字符
How do I limit user to input a single character only in C++
问:
我是初学者,我试图将用户限制为仅输入单个字符,我确实知道使用并且它只会从输入中读取一个字符,但我不希望其他字符留在缓冲区中。这是我使用 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 category
str.eof()
答:
0赞
user4581301
10/23/2017
#1
仅当您读取尝试读取流的末尾时,才会设置 eof 标志。如果读取超过流的末尾,则计算结果为 false,并且不会进入循环进行测试。如果行上有一个字符,则必须尝试读取两个字符才能触发 eof。阅读两个字符比测试它的长度要费力得多。str >> category
if (str >> category)
(str.eof())
line
while (getline (cin, line))
从控制台获取了整条线。如果你不消耗它,没关系,当你在 .stringstream
cin
while
事实上,这对你没有任何好处。确认已读取行的长度后,只需使用 .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";
}
}
}
评论
0赞
John Deveraux
10/23/2017
谢谢,这对我有很大帮助,但是你知道为什么返回的 eof 值为 0 吗?
0赞
user4581301
10/23/2017
@JohnDeveraux更新的答案来解释为什么不起作用。eof()
评论