c++ - char 输入使循环在 C++ 中不停止

标签 c++ loops

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/

相关文章:

c++ - 无法在 VScode (macOS) 中将头文件链接到我的 main.cpp(clang 错误)

c++ - 是否可以在 C++ 中创建方法调用调度程序?

c++ - boost 非默认构造类型的序列化

c# - 如何确定html中每个节点的css文本

C++ 中间函数 Hook : get register values and jump back [x86 assembly on windows]

c++ - 函数返回windows安装的驱动器?

javascript - 合并两个数组,使第一个索引都在新数组中,依此类推

jquery - 当使用 $.each 循环结果时,如何引用当前迭代的索引?

python - 创建继续嵌套 for 循环

python - 我的代码可以工作,从某种意义上说,它运行我想要它执行的操作,但是一旦用户正确猜出数字,终端就会结束并且不会循环