使用 getline 读取但用户需要使用 enter 两次
Using getline to read but user need to use enter twice
为了允许用户输入多个单词,我使用 getline
并根据 this answer 使用以下代码刷新流:
while(!everyoneAnswered()){
string name;
std::cout << "enter your name : ";
if (getline(std::cin, name)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // flush stream
std::cout << "enter your age : ";
int age;
std::cin >> age;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// stuff
}
}
问题是现在用户必须按两次输入才能接受输入。我想这是因为 getline
消耗了第一个 \n
.
我怎样才能避免这种情况,让用户只按一次回车键来验证输入?
这是一个没有冲洗的结果示例:
enter your name : foo
enter your age : 42
enter your name : enter your age : 69
--crashing because second name is empty--
这里是 与 同花顺的结果示例:
enter your name : foo
enter your age : 42
enter your name : bar
enter your age : 69
最后,没有 \n
定界符的刷新在第一次尝试时挂起,等待输入 MAX_INT
个字符。
我使用 gcc
版本 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04
)。
解决方案是也使用 getline()
读取年龄并将其解析为 int。不过,我不知道为什么混合 getline()
和 operator>>
会产生这种行为。
问题出在这两行:
if (getline(std::cin, name)) {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline
调用包含换行符,因此您的 ignore
调用将读取 下一个 行输入。
您需要在阅读 age
(使用 >>
)之后调用 ignore
,但在 getline
.
之后不需要调用
为了允许用户输入多个单词,我使用 getline
并根据 this answer 使用以下代码刷新流:
while(!everyoneAnswered()){
string name;
std::cout << "enter your name : ";
if (getline(std::cin, name)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // flush stream
std::cout << "enter your age : ";
int age;
std::cin >> age;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// stuff
}
}
问题是现在用户必须按两次输入才能接受输入。我想这是因为 getline
消耗了第一个 \n
.
我怎样才能避免这种情况,让用户只按一次回车键来验证输入?
这是一个没有冲洗的结果示例:
enter your name : foo
enter your age : 42
enter your name : enter your age : 69
--crashing because second name is empty--
这里是 与 同花顺的结果示例:
enter your name : foo
enter your age : 42
enter your name : bar
enter your age : 69
最后,没有 \n
定界符的刷新在第一次尝试时挂起,等待输入 MAX_INT
个字符。
我使用 gcc
版本 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04
)。
解决方案是也使用 getline()
读取年龄并将其解析为 int。不过,我不知道为什么混合 getline()
和 operator>>
会产生这种行为。
问题出在这两行:
if (getline(std::cin, name)) {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline
调用包含换行符,因此您的 ignore
调用将读取 下一个 行输入。
您需要在阅读 age
(使用 >>
)之后调用 ignore
,但在 getline
.