Need to write a program to take input from a user in the form of an int and validate that what they entered is not a char from az.
Is there another way to do this other than:
if((num != 'a') && (num != 'b') && (num != 'c') && (num != 'd') etc.....) printf("You entered %d", num);
是的,使用ctype.h头文件中提供的isdigit()函数
You can use the isalpha() function in the "ctype.h" header. It returns true if it is a letter. So you could do something like:
if ( !isalpha() )
{
// Do whatever
}
Here is a link to the documentation for more information.
Rather than trying to work out that it's not a character, work out that it is a digit and discard the rest using the isdigit function from ctype like below.
#include <ctype.h>
...
if (isdigit(num)) {
printf("You entered %d\n", num);
}
But this only works on single characters which is quite useless when you read in strings. So instead you could instead use the function sscanf. Like this.
int num;
if (sscanf(numstr, "%d", &num)){
printf("You entered %d\n", num);
} else {
printf("Invalid input '%s'\n", numstr);
}
Another option is to use the atoi function. But as I recall it doesn't handle errors and I find quite inferior to sscanf.
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
if( (c>='a'&& c<='z') || (c>='A' && c<='Z'))
printf("%c is an alphabet.",c);
else
printf("%c is not an alphabet.",c);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.