如何限制用户只能在 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 only\n";
}
}
我已经将它用于数字输入,eof 工作正常。
但是对于 char category
,str.eof()
似乎是错误的。
有人可以解释吗?提前致谢。
eof 标志仅在您尝试读取 过去 流的末尾时设置。如果 str >> category
读取到流的末尾,if (str >> 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";
}
}
}
我是初学者,我试图限制用户只能输入一个字符,我知道使用 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()
似乎是错误的。
有人可以解释吗?提前致谢。
eof 标志仅在您尝试读取 过去 流的末尾时设置。如果 str >> category
读取到流的末尾,if (str >> 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";
}
}
}