0

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;
3
  • 5
    The original cin >> x; all by itself (directly below the declarations of x and y) shouldn't be there. The code you "added" should be replacing that line; not adding to it. Commented Mar 18, 2018 at 8:05
  • 1
    Try to read to a string first, then try to read the integer from the string, not from cin directly, and if reading from string to integer failed, break the while loop. Commented Mar 18, 2018 at 8:07
  • as @WhozCraig said the cin >> x below declaration of x and y should not be there Commented Mar 18, 2018 at 9:48

1 Answer 1

1

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 ...     
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.