0

I don't know why my do-while loop is infinite.

int number_1, number_2 = 0;
do {
    cin.sync();
    cin.clear();
    cout << "Give number_1: ";
    cin >> number_1;
    while (cin.good() == 1) {
        number_2 += number_1;
        cout << "Give new number_1: ";
        cin >> number_1;
    };
} while (number_2<1000);

Untill i write correct number_1 everything is fine, but if i write incorrect value (for example "a") my loop becomes infinite because line 6 is ignored. Where is the clue?

SigGP
  • 716
  • 1
  • 11
  • 24
  • 1
    Are you trying to loop through inputs until their sums are over 1000? – Hill May 24 '16 at 16:03
  • 1
    maybe you should store the input in a string and check for validity? – Grady Player May 24 '16 at 16:04
  • Yes Hill, thats what i am doing. But my main problem is why line 6 is ignored and i cant put new number_1. – SigGP May 24 '16 at 16:08
  • 1
    If you don't type in a number then the input will have an error and stop working until you clear the error and flush the input – Galik May 24 '16 at 16:10
  • 1
    An if you do type in a number it will keep looping asking you for anoher one because there is no way out of that loop (unless you make an error) – Galik May 24 '16 at 16:11
  • And how can i fix it? For this reason i have put cin.sync() and cin.clear(); – SigGP May 24 '16 at 16:12
  • 1
    Possible duplicate of: https://stackoverflow.com/questions/28532530/infinite-loop-without-accepting-input or https://stackoverflow.com/questions/20622338/infinite-loop-when-reading-in-input-file or https://stackoverflow.com/questions/19521320/why-do-i-get-an-infinite-loop-if-i-enter-a-letter-rather-than-a-number – Galik May 24 '16 at 16:15
  • 1
    `cin.sync()` does not remove characters from input queue. In fact it does not do anything you should be concerned with unless you know exactly what it does on specific OS/compiler/library/stream type. – Revolver_Ocelot May 24 '16 at 16:21

0 Answers0