0

There is a loop i want to run and check for valid input, if not valid jump out the itteration and start at the beginning of the loop where i ask for input.

close = false;
int direction
while (!close){

    if (!(cin >> direction)){
        cout << "not valid: " << endl;
        continue;
    }
    close = true;
}

However when I run it I can only enter the direction one time and not reenter it when continue is reached. How can I end a itteration and let the user retry.

When adding the variable to the while loop and remove from above the while loop (it's local to the while loop and destroyed outside than right?) like

while (!close){
    int direction;
    ////
 }

it also dosn't work. I know the whole part of code could be better but I just started with c++ and am trying to understand why it dosn't work like i expect.

Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169
  • 2
    The stream is an error state where it ignores further input. You need to `clear` that, and consume any buffered characters. – Cheers and hth. - Alf Sep 19 '15 at 18:49
  • Instead of the boolean variable and `continue`, consider a `while(true)` and a `break`. ;-) And even better (in my very personal opinion, but I can argue it), consider a `for(;;)` instead of `while(true)`. It's less to write, probably easier to recognize and doesn't cause one compiler to emit silly-warnings. – Cheers and hth. - Alf Sep 19 '15 at 18:50
  • Sorry for my laziness, I don't want to write the same answer again today. Research more before asking here please. – πάντα ῥεῖ Sep 19 '15 at 18:57
  • 1
    @πάνταῥεῖ: The question is why you wrote that answer once today, when there are a thousand better ones to the exact same question. – Ben Voigt Sep 19 '15 at 18:59
  • @πάνταῥεῖ The answer you posted has a upvoted comment which states "@user2546419 yes, after an error cin just returns immediately without doing anything. – Galik 8 hours " If thats the case it would return and still enter the loop. I dont see how the question you marked as related answers my question, it's only a solution not an explenation and i would like to understand the code. – Sven van den Boogaart Sep 19 '15 at 18:59
  • @BenVoigt Could well be, doesn't invalidate it being a dupe of that one. – πάντα ῥεῖ Sep 19 '15 at 19:01
  • @πάνταῥεῖ: But sending this asker to a crappy answer (no explanation about stream state)? Use the best duplicate you can find, even if someone else's answer earns the reputation. – Ben Voigt Sep 19 '15 at 19:03
  • @BenVoigt Give the better one, reopen and dupe hammer again, as you did actually. – πάντα ῥεῖ Sep 19 '15 at 19:05

1 Answers1

0

Why not use a while loop?

while(! (cin >> x)) {
    cout << "invalid input " << endl;
}
turbo_laser
  • 261
  • 3
  • 16