2

I'm trying to print an error message if the user does not enter anything into the input prompt, and if what they enter is zero or less.

void checkScoreInputed(int* qaltScores, int i){
    while(true){
        // cin.clear(); here?
        if ((cin >> qaltScores[i]) && (qaltScores > 0)){
            // also tried placing cin.clear() here. 
            break;} else // else is optional
        cout << "Please supply a positive number for the score: ";
    }
}

I've tried placing cin.ignore() and cin.clear() both before and after the if statement, but I am still getting an infinite loop of cout << "Please supply...." after the user enters a non-integer value, like a character. How can I fix this?

LazerSharks
  • 3,089
  • 4
  • 42
  • 67
  • Thing is, I'm not sure where I should place the clear(), if necessary. – LazerSharks Mar 02 '13 at 22:47
  • 1
    You need to call them after the input goes into a bad state. In your code, that is most logically right with the output. – chris Mar 02 '13 at 22:49
  • @chris Thanks Chris, your comment, which should be an answer, helped and made it work! – LazerSharks Mar 02 '13 at 22:50
  • 1
    The answer provided that around the same time as me :) I was going for the very brief explanation of why you put it there. – chris Mar 02 '13 at 22:56

1 Answers1

2

You forgot the [i] in

if ((cin >> qaltScores[i]) && (qaltScores[i] > 0))
                                         ^^^

Without it, you're checking the value of the pointer, not the number you've just read.

You also need to call cin.clear() and cin.ignore().

void checkScoreInputed(int* qaltScores, int i) {
    while(true) {
        if ((cin >> qaltScores[i]) && (qaltScores[i] > 0)){
            break;
        }
        cout << "Please supply a positive number for the score: ";
        cin.clear();
        cin.ignore(10000,'\n');
    }
}

See Why would we call cin.clear() and cin.ignore() after reading input?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012