【发布时间】:2015-05-24 17:24:01
【问题描述】:
我正在使用这段代码做某事 -
// Initialize variables
double x;
...
// Here is where I'm facing problem
while (cin >> x){
if (x == '|'){
cout << "\nBreaking the loop\n"; // Edit1: Unable to produce output
break;
}
// Do something
...
}
// Do some other things
cout << "\nAfter the loop"; // Edit1: This gets executed,
cin >> x; // but this doesn't.
...
// End
但是,当我输入 '|' 时,窗口关闭,甚至没有输出这个 - Breaking the loop 并且不执行 while 循环之后的语句(我认为)。
我正在使用 Visual C++。
为什么会这样?有什么解决办法吗?
【问题讨论】:
-
它破坏了外观,因为 cin >> x 评估为 false 为 '|'不能初始化为双精度。
-
|不是double值的文本表示中的有效字符。因此,cin >> x在输入流中遇到此字符时会设置cin.failbit()。这会导致循环条件变为false。 -
试试
cout << "\nBreaking the loop" << endl; -
@IvanWalulya:但是即使我使用
int,而不是double,它也会产生输出Breaking the loop,但窗口仍然会再次关闭,并且在一段时间之后它不会执行任何代码循环。 -
一旦
failbit在流上设置,它将保持设置状态。您可以使用cin.clear()重置它。此外,|字符从未从输入流中提取 - 如果您尝试再次读取double,则读取的第一个字符将是|,它会再次以与第一次相同的方式失败。您可以使用cin.ignore()跳过某些字符。
标签: c++ visual-c++