0

I'm trying to validate the user inputs. If the user inputs anything but an integer it should stay in the While loop. But when I give the program a "w" for instance the program just endlessly prints "Please input integer" and I have to stop the program.

int MAns1 = 0
while (!(cin >> MAns1))
{
    cout << "\nPlease Enter An Integer: ";
    cin.clear();
}
Yannick Meeus
  • 5,643
  • 1
  • 35
  • 34
RIDDLEisVoltron
  • 31
  • 1
  • 1
  • 5
  • This is totally duplicate. My Bad. Also I figured it out: while (!(cin >> MAns1)) { cout << "\nPlease Enter An Integer: "; cin.clear(); cin.ignore(INT_MAX, '\n'); } – RIDDLEisVoltron Jul 21 '15 at 15:39

1 Answers1

0

Because you should be testing (cin >> MAns1), not !(cin >> MAns1). I would do something like this though:

#include<iostream>
using std::cin;
using std::cout;

int main() { 
    int MAns1 = 0;
    for (;;)
    {
        cout << "\nPlease Enter An Integer: ";
        cin >> MAnsi;

        // did the last read succeed?
        if(!cin) {
          // it did *not* succeed.
          break;
        }
    }
}
Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88