isdigit not working as I expected

Jul 2, 2013 at 8:12pm
Hello all!

I have a specific code question. I'm trying to ensure that the character entered is a digit. If it is a digit, the program should continue. If it's not a digit, an error message should occur and a prompt for another input. Here is the code, my questions are in the comments...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>
#include <iomanip>
#include <cctype>		//prototypes for character functions
using namespace std;

//I've edited out the non pertinent code...
int main ()
{
int isDigit;
int userNum;

    cout << "Enter an integer. Enter -999 to quit: ";
    cin  >> userNum;
	
	isDigit = (isdigit (userNum));  //if the user enters a number, shouldn't this return true?  It's returning false even when a number is entered...
	while ( isDigit == false )
		{
		cout << "Your input is not valid.  Please enter a number from 0-9: ";
		cin >> userNum;
                isDigit = (isdigit (userNum)); 
		}

Thanks!
Last edited on Jul 2, 2013 at 8:36pm
Jul 2, 2013 at 8:17pm
Please supply us with the rest of your code... It may be the way that you edited it, but this makes your program seem recursive...

- Kyle
Last edited on Jul 2, 2013 at 8:18pm
Jul 2, 2013 at 8:20pm
isdigit works with single characters and returns true for '0' to '9'.
Jul 2, 2013 at 8:24pm
Function isdigit is applied to object of the type char. Though its argument is declared as int nevertheless it is used with characters that is it considers only the lowerst byte of the argument and checks whether its value is between '0' and '9' inclusively.


Consider an example

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <iomanip>
#include <cctype>

int main()
{
   for ( char c = '0'; c <= '9'; c++ )
   {
      std::cout << c << " is digit " << std::boolalpha << ( std::isdigit( c ) != 0 ) << std::endl;
   }
}
Last edited on Jul 2, 2013 at 8:33pm
Jul 2, 2013 at 8:24pm
Oh, sorry about that... I failed to realize isDigit vs. isdigit. Peter87 is correct.
Jul 2, 2013 at 8:24pm
//I've edited out the non pertinent code...

I think the declaration of userNum is extremely pertinent to the question.
Jul 2, 2013 at 8:36pm
Thank you very much KyleMiles, vlad and Peter87, that makes sense. Chervil you are right that declaration is pertinent, my mistake for not adding to the code. I've corrected it for the post.
Topic archived. No new replies allowed.