检查用户是否在C中输入字母或数字

是否有一种简单的方法可以调用C脚本来查看用户是否输入了英文字母中的字母? 我在想这样的事情:

if (variable == a - z) {printf("You entered a letter! You must enter a number!");} else (//do something} 

我想检查以确保用户没有输入字母,而是输入一个数字。 想知道是否有一种简单的方法来拉动每个字母而无需手动输入字母表中的每个字母:)

 #include  if (isalpha(variable)) { ... } 

最好测试十进制数字本身而不是字母。 isdigit 。

 #include  if(isdigit(variable)) { //valid input } else { //invalid input } 

isalpha()将一次测试一个字符。 如果用户输入了像23A4这样的数字,那么你想测试每个字母。 你可以用这个:

 bool isNumber(char *input) { for (i = 0; input[i] != '\0'; i++) if (isalpha(input[i])) return false; return true; } // accept and check scanf("%s", input); // where input is a pointer to a char with memory allocated if (isNumber(input)) { number = atoi(input); // rest of the code } 

我同意atoi()不是线程安全的和不推荐使用的函数。 您可以编写另一个简单的函数来代替它。

除了isalpha函数,你可以这样做:

 char vrbl; if ((vrbl >= 'a' && vrbl <= 'z') || (vrbl >= 'A' && vrbl <= 'Z')) { printf("You entered a letter! You must enter a number!"); } 

strto*()库函数在这里派上用场:

 #include  #include  #include  #define SIZE ... int main(void) { char buffer[SIZE]; printf("Gimme an integer value: "); fflush(stdout); if (fgets(buffer, sizeof buffer, stdin)) { long value; char *check; /** * strtol() scans the string and converts it to the equivalent * integer value. check will point to the first character * in the buffer that isn't part of a valid integer constant; * eg, if you type in "12W", check will point to 'W'. * * If check points to something other than whitespace or a 0 * terminator, then the input string is not a valid integer. */ value = strtol(buffer, &check, 0); if (!isspace(*check) && *check != 0) { printf("%s is not a valid integer\n", buffer); } } return 0; } 

你也可以用几个简单的条件来检查字符是否是字母

 if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z')) { printf("Alphabet"); } 

或者您也可以使用ASCII值

 if((ch>=97 && ch<=122) || (ch>=65 && ch<=90)) { printf("Alphabet"); } 
 int strOnlyNumbers(char *str) { char current_character; /* While current_character isn't null */ while(current_character = *str) { if( (current_character < '0') || (current_character > '9') ) { return 0; } else { ++str; } } return 1; }