Reputation:
I have a function which takes an integer input by the user.
So I have:
scanf("%d, &x);
And then, the function:
test(int x);
Inside test(), I wanna check if the input is a digit or a character, so I tried:
if (isdigit(x))
// piece of code
printf("Done!\n");
else
printf("Bye!\n");
However, isdigit() does not seem to be working as the program is outputting "Bye!" immediately. What could be the problem?
Thanks.
Upvotes: 1
Views: 1631
Reputation: 1538
The C library function void isdigit(int c )
checks if the passed character is a decimal digit character.
The isdigit() function
returns non-zero if c is a decimal digit otherwise 0
.The input argument is an int
, the value of which the application shall ensure is a character representable as an unsigned char
or equal to the value of the macro EOF
. i.e
ensure that your value is enclosed in single quotes.
You also seemed to have a ;
after the if statement which shifts the expected control flow.
char x;
scanf(" %c", &x);
if (isdigit(x))
printf("Done!\n");
else
printf("Bye!\n");
Upvotes: 1
Reputation: 58271
You are passing integer not char!
isdigit(x)
check whether x
is a digit char e.g. '0'
, '1'
but not 0
, 1
what you are passing.
It behaves like:
isdigit('h') returns 0
isdigit('1') returns 1
isdigit(1) returns 0 // your are passing this
Read manual:
Standard C Library Functions ctype(3C)
isdigit()
Tests for any decimal-digit character.
Upvotes: 4
Reputation: 153457
Suspect OP wants to read a char
char x; // new type
scanf(" %c", &x); // new format specifier
if (isdigit(x)) // remove ;
// piece of code
printf("Done!\n");
else if (isalpha(x)) // added test @Joachim Pileborg
printf("Is a alpha!\n");
else
printf("Bye!\n");
Upvotes: 0
Reputation: 20764
remove the semicolon:
if (isdigit(x)); // <===
Because of the semicolon, if it is a digit you execute an empty statement.
Upvotes: 1
Reputation: 7960
isdigit
tests a character:
isdigit('5') == true;
isdigit(5) == false;
Upvotes: 1