如何限制用户仅在C++中输入单个字符
How do I limit user to input a single character only in C++
我是初学者,我试图限制用户只输入一个字符,我知道使用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";
}
}
}
相关文章:
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 使用单个变量对字符输入进行计数
- 是否可以将键盘输入绑定到 Win32 中的单个应用程序?
- 编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
- 将单个字符串/字符输入串行监视器
- 有没有办法将两个输入图像堆叠到卤化物发生器中的单个 4 维缓冲区中?
- 如何使用 std::cout 或 std::ofstream 作为单个函数的输入?
- 如何从用户那里获取单个字符,直到他输入"."或输入
- QuickSort方法仅使用单个向量作为C 中的输入参数
- 是否可以使整数仅收到一个单个数字而不是两个接收输入
- 检查不作为单个条目的STDIN输入
- 输入到字符串流并在单个语句中转换为字符串.可以没有帮助程序类
- 如何从包含多个句子的输入文件中表达单个单词.C
- 如何限制用户仅在C++中输入单个字符
- 来自单个数字输入的Arduino读取脉冲宽度频率和占空比
- (DirectX 11)单个顶点缓冲区是否可以一次绑定到多个 IA 输入槽
- 接受来自单个输入C++的字符串或数字
- C++输入失败:单个语句中有多个输入
- C++ 使用单个输入字节文件的不同部分实例化堆栈上的成员类
- 比较字符串中的单个字符.在用户输入的字母字符串中查找辅音