Using isdigit()

So i'm making a small function to add 10 digits that the user has input and then i check if that input is a digit or not. but it's not working.

Whenever i put anything other than an integer, i get an infinite loop: http://i.imgur.com/sMhvaHf.png

and if i do put in an integer, it just tells me "invalid input. Try again" just like i have it set on line 27

Any advice?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <ctype.h>
using namespace std;
 
int main(){
    int iSum = 0;
    cout << "Enter 10 integers. \n";
    for (int i=1; i<=10; i++){
        int iInput = 0;
 
        bool bInvalid = true;
        do{
            cout << "Enter the " << i;
            if (i == 1)
                cout << "st number: ";
            else if (i == 2)
                cout << "nd number: ";
            else if (i == 3)
                cout << "rd number: ";
            else
                cout << "th number: ";
            cin >> iInput;
 
            if (isdigit(iInput))
                bInvalid = false;
            else
                cout << "Invalid input. Try again.\n\n";
        }
        while(bInvalid);
 
        iSum += iInput;
    }
    cout << "The sum of these 10 numbers is: " << iSum;
 
    return 0;
}
Last edited on
isdigit() is meant to be passed chars. For example !isdigit('c') but isdigit('4').
iInput is already a number, so if we follow the logic you were trying to use, isdigit() should always return true (all ints are numbers).

operator>>() returns false if the input couldn't be put in the right hand operand. In other words, if (cin >> iInput) can tell you if the input is invalid.
Topic archived. No new replies allowed.