c++ - 为什么我在 C++ 中的 while 循环不能正确运行?

标签 c++ while-loop

我只是编程新手,我试图编写一个 while 循环,只要输入 (num) 不是不以零结尾的整数,它就会运行。当我输入一个以零结尾的数字时,程序会正确运行循环,但是当我输入一些无意义的东西时,比如 rofl,程序只会打印 The input is not valid. 并且不会重复循环。我试图寻找解决方案,但一个小时后我仍然卡住了。任何人都可以在这里帮助我吗?非常感谢!

void rev_sum() {
    int num;
    int a = 1;
    while (a < 2) {
        cout << "Please input a natural number without zero at the end:\n";
        cin >> num;
        if (!cin) {
            cout << "The input is not valid.\n";
            cin.clear();
            cin.ignore(INT_MAX);
        }
        if (num % 10 == 0) {
            cout << "The number cannot have zero at the end\n";
        } else {
            cout << "gj\n";
            break;
        }
    }
}

最佳答案

尝试替换

cin.ignore(INT_MAX);

cin.ignore(numeric_limits<streamsize>::max(), '\n');

并改变

if (num % 10 == 0)

else if (num % 10 == 0)

您的最终代码应如下所示:

void rev_sum() {
    int num;
    int a = 1;
    while (a < 2) {
        cout << "Please input a natural number without zero at the end:\n";
        cin >> num;
        if (!cin) {
            cout << "The input is not valid.\n";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
        else if (num % 10 == 0) {
            cout << "The number cannot have zero at the end\n";
        } else {
            cout << "gj\n";
            break;
        }
    }
}

关于c++ - 为什么我在 C++ 中的 while 循环不能正确运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26047714/

相关文章:

c++ - "gdb"调试器奇怪地跳过断点

linux - 如何在shell脚本中添加缩进

java - jTable swing获取输入问题

c++ - 哪个 C++ IDE 支持快速 TDD 工作流程和 Google 或 Boost 测试框架?

c++ 将一个类中的对象推送到另一个类中的 vector 中?

c++ - C++中如何调用指针成员变量的构造?

java - java代码中循环内的增量问题

sql - oracle中的while循环

javascript - 在循环内映射数组

c++ - GCC 和预编译 header