Help with obtaining a number from cin

Here's the snippet from my code


1
2
3
4
5
6
7
cin >> balance;
    while (isdigit(balance))
    {
        cout << "\n" << balance << " is not a valid balance.";
        cout << "\nEnter the beginning balance: ";
        cin >> balance;
    }



The while loop seems to work in the sense that the code runs correctly afterwards if it is an actual number typed in. If a letter, like 'r', is entered instead of a number it's almost as if the buffer fills up and somehow skips the while loop above, getting stuck in an infinite loop that comes later in the program. I will post the full code if it would be helpful, but I basically just need a way to force the user to enter a number and not a letter or string

edit:

When I modify the code to this:

1
2
3
4
5
6
7
8
while (!(cin >> balance))
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "\nInvalid input. Please try again.";
        cout << "\nEnter the beginning balance: ";
        cin >> balance;
    }


It appears to give the error correctly when a letter is typed but for some reason entering a number makes the program wait until a second number is entered that it then uses for my variable balance.

edit2:

This appears to work

1
2
3
4
5
6
7
8
9
cout << "\nCheckbook Balancing Program\n\n";
    cout << "Enter the beginning balance: ";
    while (!(cin >> balance))
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid input. Please try again.";
        cout << "\n\nEnter the beginning balance: ";
    }


But I'm not clear on why when there's no line asking for the input between the prompt for the beginning balance and the while loop :/
Last edited on
In the following code you are asking for the balance twice, once in the while loop condition, and again at the end of the loop.
1
2
3
4
5
6
7
8
while (!(cin >> balance)) // Retrieve the balance from the user.
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "\nInvalid input. Please try again.";
        cout << "\nEnter the beginning balance: ";
        cin >> balance;  // Retrieve the balance from the user again.
    }


In your last snippet you only have one cin, the one in the while condition. Because you only have one cin statement your program should work correctly.

Jim
Thank you for your reply. I've taken some VERY elementary courses in C and java and never asked for any input in a loop condition. It makes sense the way you put it though, Thanks a bunch
Topic archived. No new replies allowed.