int main()
{
std::cout << "Enter numbers separated by whitespace (use -1 to quit): ";
int i = 0;
while (i != -1) {
std::cin >> i; // 不良的形式 — 见如下注释
std::cout << "You entered " << i << '\n';
}
}
该程序没有检查键入的是否是合法字符。尤其是,如果某人键入的不是整数(如“x”),std::cin流进入“失败状态”,并且其后所有的输入尝试都不作任何事情而立即返回。换句话说,程序进入了死循环;如果42是最后成功读到的数字,程序会反复打印“You entered 42”消息。
检查合法输入的一个简单方法是将输入请求从 while 循环体中移到 while 循环的控制表达式,如:
#include <iostream>
int main()
{
std::cout << "Enter a number, or -1 to quit: ";
int i = 0;
while (std::cin >> i) { // 良好的形式
if (i == -1) break;
std::cout << "You entered " << i << '\n';
}
}
这样的结果就是当你敲击end-of-file,或键入一个非整数,或键入 -1 时, while 循环会退出。
[15.3] 那个古怪的while (std::cin >> foo)语法如何工作?
[Recently changed so it uses new-style headers and the std:: syntax (on 7/00). Click here to go to the next FAQ in the "chain" of recent changes.]
“古怪的 while (std::cin >> foo)语法”的例子见前一个FAQ。
[15.4] 为何我的输入处理会超过文件末尾?
[Recently changed so it uses new-style headers and the std:: syntax (on 7/00). Click here to go to the next FAQ in the "chain" of recent changes.]
因为只有在试图超过文件末尾后,eof标记才会被设置。也就是,在从文件读最后一个字节时,还没有设置 eof 标记。例如,假设输入流映射到键盘——在这种情况下,理论上来说,C++库不可能预知到用户所键入的字符是否是最后一个字符。
如,如下的代码对于计数器 i 会有“超出 1”的错误:
int i = 0;
while (! std::cin.eof()) { // 错误!(不可靠)
std::cin >> x;
++i;
// Work with x ...
}
你实际需要的是:
int i = 0;
while (std::cin >> x) { // 正确!(可靠)
++i;
// Work with x ...
}