Reputation: 1
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;
Upvotes: 0
Views: 3622
Reputation: 596703
The problem is that you are reading from cin
1 time too many:
int x, y;
cin >> x; // <-- reads an int, without validation!
while ( ! ( cin >> x )) { // <-- reads ANOTHER int!
You need to get rid of the first read before entering the while
loop. Let the loop alone do the reading:
#include <iostream>
#include <limits>
using namespace std;
main () {
int x, y;
// <-- NO READ HERE!
cout << "Enter a number: ";
while (!(cin >> x)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter a number: ";
}
// same as above, for y ...
}
Alternatively, use a do..while
loop instead:
#include <iostream>
#include <limits>
using namespace std;
main () {
int x, y;
// <-- NO READ HERE!
do {
cout << "Enter a number: ";
if (cin >> x) break;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while (true);
// same as above, for y ...
}
Upvotes: 1