program_g21 program_g21 - 23 days ago 6
C++ Question

isdigit() isn't working in a simple program?

#include<iostream.h>
#include<conio.h>
#include<ctype.h>
void main()
{
clrscr();
int a;
cout<<"Enter a digit";
cin>>a;
if(isdigit(a))
{
cout<<"You have entered a digit";
}
else
{
cout<<"Not a digit";
}
getch();
}


The code shows no errors, but every time I enter a digit it displays "Not a digit".

Answer
int a;
std::cin >> a;

This code (or your somewhat antiquated variant) reads text from the console and converts that text into an integer value. So if you type 0 at the console, the value of a will be 0, not '0'. isdigit tells you whether the character value that you pass to it represents a digit, and 0 does not, so the result is almost certainly correct. If you instead read the value into a variable of type char you'll get the behavior that you expect.

char a;
std::cin >> a;