I would like my code to only input integers. The code below does it's job correctly and asks the user for input if an integer was not used. However, after adding the code:
while ( ! ( cin >> x ))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter a number: ";
}
into the code below, it only works when I enter a non-integer first. Otherwise if I enter an int first, the program doesn't move on to the next statement and doesn't do anything. My reasoning was that if x = int then the while loop would not be started. So why is it that adding the code messes up the remaining code.
#include <iostream>
#include <limits>
using namespace std;
main ()
{
cout << "Enter a number: ";
int x, y;
cin >> x;
while ( ! ( cin >> x ))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter a number: ";
}
cout << "Enter a number: ";
cin >> y;
cin >> x;all by itself (directly below the declarations ofxandy) shouldn't be there. The code you "added" should be replacing that line; not adding to it.cindirectly, and if reading from string to integer failed, break the while loop.cin >> xbelow declaration of x and y should not be there