【问题标题】:Program goes into infinite loop when I input "9+" [duplicate]当我输入“9+”时程序进入无限循环[重复]
【发布时间】:2015-10-12 09:47:05
【问题描述】:
#include <iostream>
using namespace std;

void check_positive () {
    cout << "Number given must be positive. Please try again." << endl;
}

int main() {
    int pesos, interest, compound, year;
    do {
        cout << "How many pesos did you deposit? ";
        cin >> pesos;
        if (pesos <= 0) {
            check_positive();
    }
    } while (pesos <= 0);
    do {
        cout << "What is the interest? ";
        cin >> interest;
        if (interest <= 0) {
            check_positive();
        }
    } while (interest <= 0);
}

每当我运行此代码并在第一个循环期间输入“9+”作为输入时,第一个循环结束,但在第二个循环开始后立即进入无限循环。为什么会这样?

【问题讨论】:

  • 因为你从不检查你的输入是否成功。
  • 您预计会发生什么?尽可能具体。你认为什么代码可以处理这种情况,你认为它是如何处理的?
  • stackoverflow.com/questions/19521320/… 已经在这里讨论过

标签: c++


【解决方案1】:

您输入了不是数字的字符9+,并尝试将它们加载到只能接受数字的整数变量int pesos。 Cin 无法将 9+ 转换为数字,因此它进入了失败状态,您可以通过更改第一个循环来检查,如下所示:

do {
    cout << "How many pesos did you deposit? ";
    cin >> pesos;

    if (cin.fail()) {
        cout << "You didn't enter a number!";
        return EXIT_FAILURE;
    }

    if (pesos <= 0) {
        check_positive();
}

请注意,您也可能在第二个循环中遇到同样的问题,因此您需要再次检查 cin.fail()

补充阅读:ios::fail() reference

【讨论】:

  • 但是为什么不重复第一个循环而不是第二个循环,因为变量“pesos”是具有不可接受值的那个?
  • 我认为这取决于cin的实现,但可能是因为cin读取9并将其放入pesos变量,然后由于+而进入失败状态,因为现在pesos &gt; 0它退出第一个循环。当您尝试在失败状态下使用 cin 读入int interest 时,它会立即返回而不读取任何输入。
  • 哦,好的,谢谢大家的帮助 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
相关资源
最近更新 更多