[英]Why doesn't std::cin.clear() work in this simple program?
I was solving some exercises to pass the time, and I encountered a behaviour I didn't understand, I am going to explain: 我正在解决一些打发时间的练习,遇到一种我不了解的行为,我将解释:
The exercise: 练习:
Write a program that reads and stores a series of integers and then computes the sum of the first
N
integers.编写一个程序,该程序读取并存储一系列整数,然后计算前
N
整数的和。 First, ask forN
, then read the values into a vector, then calculate the sum of the firstN
values.首先,要求
N
,然后将值读入向量,然后计算前N
值的总和。
Since I asked for N
as the second step: 由于我要求
N
作为第二步:
In the second std::cin
( std::cin >> values_to_compute
) it has to leave the while statement to continue the program, "only possible if" what is read is not a double. 在第二个
std::cin
( std::cin >> values_to_compute
)中,它必须离开while语句才能继续执行程序,“只有在读取的内容不是双std::cin >> values_to_compute
才可能。 So I can type, for example; 例如,我可以输入; 'k' or "how are you?"
“ k”或“你好吗?” or Ctrl + Z (I am on Windows 10).
或Ctrl + Z键(我在Windows 10上)。
int main() {
try {
double holder {0};
std::vector<double> values;
while (std::cin >> holder) {
values.push_back(holder);
}
std::cin.clear();
std::cout << "Out of the loop, now entering to the other std::cin\n";
int values_to_compute {0};
std::cin >> values_to_compute;
std::cout << "Computing...\n";
double result_computed {0};
for (int i {0}; i < values_to_compute; ++i) {
result_computed += values[i];
}
std::cout << "Result computed " << result_computed << '\n';
system("pause");
return 0;
}
catch (std::runtime_error& e) {
std::cerr << e.what() << '\n';
system("pause");
return 1;
}
}
Ok so? 好吧 So...
std::cin
leaves the while in a not good() state. 所以...
std::cin
使那一会儿处于std::cin
好的状态。 I have to call std::cin.clear()
to be able to use std::cin
again. 我必须调用
std::cin.clear()
才能再次使用std::cin
。
Ok, and? 好吗 Well, if I type Ctrl + Z to exit the
while
loop, the std::cin.clear()
works; 好吧,如果我按Ctrl + Z退出
while
循环,则std::cin.clear()
可以工作; if I type something that is not Ctrl + Z the std::cin.clear()
doesn't work. 如果我输入的不是Ctrl + Z,则
std::cin.clear()
不起作用。
I want to know the why of that behaviour. 我想知道为什么这样做。
That's because std::cin::clear
clears the error state of cin
but it does not remove the data from the stream. 这是因为
std::cin::clear
清除的错误状态cin
,但它不从流中删除数据。 You can use std::cin::ignore()
to read and discard a line of text before reading values_to_compute
. 在读取
values_to_compute
之前,可以使用std::cin::ignore()
读取和丢弃一行文本。
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Make sure to #include <limits>
to get std::numeric_limits
. 确保
#include <limits>
以获得std::numeric_limits
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.