C++程序如下
#include <iostream>
using namespace std;
int main(void) {
/* temporary storage for the incoming numbers */
int number;
/* we will store the currently greatest number here */
int max = -100000;
/* get the first value */
cin >> number;
/* if the number is not equal to -1 we will continue */
while(number != -1) {
/* is the number greater than max? */
if(number > max)
/* yes – update max */
max = number;
/* get next numbet */
cin >> number;
}
/* print the largest number */
cout << "The largest number is " << max << endl;
/* finish the program successfully */
return 0;
}
如果我输入一些数字,例如 69 10 -1
。它会起作用。
但是当我输入一些字符时,即使我输入-1
,它也没有停止。
例如 a a -1 -1 -1
为什么?
最佳答案
您需要在每次读取后检查流状态。
字母a
不是正确的十进制数字,因此输入失败。当输入失败时,它会设置一个失败位,这会导致所有后续输入失败或不发生。
总是在读取变量后检查输入状态。
如果您想继续,恢复是清除
状态。
关于c++ - char 输入使循环在 C++ 中不停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35105180/