0
#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);
}

Whenever I run this code and enter "9+" as the input during the first loop, the first loop ends but then goes into an infinite loop immediately after the second loop starts. Why does this happen?

Paul R
  • 208,748
  • 37
  • 389
  • 560

1 Answers1

0

You entered characters 9+ that are not a number, and tried to load them into an integer variable int pesos which can only accept numbers. Cin couldn't convert 9+ to a number and so it entered fail state which you can check by changing your first loop like so:

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();
}

be wary that you can also have the same problem in the second loop and thus you need to check cin.fail() again there

For additional reading: ios::fail() reference

Ritave
  • 1,333
  • 9
  • 25
  • But why didn't the first loop repeat instead of the second loop since the variable "pesos" was the one that had the unacceptable value? – Joshua Franco Pili Oct 12 '15 at 10:23
  • I think it depends on the implementation of cin, but probably because cin read `9` and put it into pesos variable, and then got into fail state due to `+`, since now `pesos > 0` it exits the first loop. And when you tried to use cin in failed state to read into `int interest` it returns immediately without reading any input. – Ritave Oct 12 '15 at 10:31
  • Oh okay, thank you for all the help :) – Joshua Franco Pili Oct 12 '15 at 10:45