How does the C language distinguish between input being a character or a number?
In C language, you can determine whether the input is a character or a number by checking the ASCII value of the input character.
To determine if the input is a number, you can check if the ASCII value of the character falls within the range of ‘0’ to ‘9’. You can use the following code to do so:
#include <stdio.h>
int main() {
char input;
printf("请输入一个字符:");
scanf("%c", &input);
if (input >= '0' && input <= '9') {
printf("输入的是数字\n");
} else {
printf("输入的是字符\n");
}
return 0;
}
In this example, first a character input from the user is read using the scanf function and stored in the variable input. Then a conditional statement using if is used to determine if the input character is a number. If the value of input is greater than or equal to the character ‘0’ and less than or equal to the character ‘9’, it means that the input is a number, and the program will output “Input is a number”. Otherwise, the input is a character, and the program will output “Input is a character”.