我改编了 Bjarne Stroustrup 的《编程:C++ 原理与实践》中的这段代码,试图检查给定的输入是否有效:
#include <iostream>
using namespace std;
int main()
{
cout << "Please enter your first name and age: ";
string first_name = "???";
int age = -1;
cin >> first_name >> age;
while (!cin) {
cin.clear();
cout << "Sorry, can you enter that again? ";
cin >> first_name >> age;
}
cout << "Hello, "<<first_name<<"! (age "<<age<<")\n";
return 0;
}
这按预期工作,除了单词 "Sorry, can you enter that again? "
被打印两次,一次在第二次输入之前,一次在第二次输入之后。
有人知道为什么会这样吗?谢谢。
最佳答案
仅仅清除失败位是不够的,您还必须清除输入缓冲区中所有剩余的字符。此外,代码看起来比必要的更复杂。以下作品:
std::string name;
int age;
std::cout << "Please enter your name & age: ";
while (not (std::cin >> name >> age)) {
std::cout << "Sorry, can you enter that again? ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "Hello " << name << " (" << age << ")\n";
哦,是的,别忘了刷新输出流,我认为这不会自动为您完成。
也就是说,标准输入/输出流是流,所以它们并不真正适合交互式输入。您应该为此使用适当的库,例如 readline
或 ncurses
。
为了说明为什么这很重要,假设用户输入“foo42
”并按下回车键。你希望程序现在说“对不起,你能再输入一次吗?”但事实并非如此。相反,它温顺地等待用户输入第二个 token 。从可用性的角度来看,这肯定不是您所期望的。
关于C++ cout in while 循环打印两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12422331/