Firstly:
char t[] = "";
creates a buffer of exactly one character, then
scanf("%s", t);
will overrun that buffer for anything but an empty string input. Making scanf()
safe from overrun is not straightforward, but even then most naive implementation will have a practical buffer length e.g. ;
char t[128] = "" ;
If the expectation is to enter a string that can be converted to an int
, then 10 decimal digits is sufficient for all positive 32bit integers.
scanf("%10s", t);
char
and int
are data types, here the user only ever enters a string. Your question is really whether the user has entered somthing that may be interpreted as an integer or not.
isalpha()
and isdigit()
operate on single characters, but t
is a string.
The following will check the first character of the string t
:
if( isdigit(t[0]) )
{
printf("It's digit\n");
}
else
{
printf("It's not a digit\n");
}
Note that it makes little sense testing for isalpha()
because the union of all digits + all alpha, is still only a subset of all characters.
If in fact you simply wish to verify that the entire string is numeric then:
for( int i = 0; t[i] != 0 && isdigit(t[i]) i++ )
{
// nothing
}
if( t[i] == 0 )
{
printf("It's numeric\n");
}
else
{
printf("It's not entirely numeric\n");
}
Even then it is not a given that the numeric string can be represented by an int
; it also has to be in range. You might also want to consider the possibility of a -/+ sign at the start, and might consider ignoring trailing non-numeric digits.