while-test problem

closed account (jLNv0pDG)
1
2
3
4
5
6
7
8
9
10
11
12
#include <cctpye>
...
cout << "Enter a negative number or non-numeric input to quit: ";

int money = 0;
int total = 0;

while (isdigit(money) && money >= 0)
{
    total += money;
    cin >> money;
}


Basically, I want the program to keep adding numbers until you enter a negative number or a non-numeric character. However, I don't think the while test, specifically the isdigit bit is working right. The program doesn't let me input any data; it just displays random numbers as output. Can anyone tell me why it's not working or tell me how to fix it?
Last edited on
isdigit() is used to test whether a character represents a digit. For example, isdigit('5')!=0, but isdigit('A')==0. It only takes int to account for wide characters. An int will always be number so it makes no sense to test whether it's a digit.

To test whether a number was entered, test (cin >>money). If it's false, something other than a number was entered.
Last edited on
closed account (jLNv0pDG)
Thanks helios, I see what you mean now.

cin.fail() seems like what I should be using then.
No, that's not what I meant.
if (cin >>money) is what I meant.
closed account (jLNv0pDG)
Ahhh. So, if (cin >>money) allows me to enter a number, assign it to money and check that it is numeric all in one shot? :)

while (cin >> money && money >= 0) seems like it runs perfectly...
That is correct.
Topic archived. No new replies allowed.