有没有一种简单的方法可以调用 C 脚本来查看用户是否输入了英文字母表中的字母?我在想这样的事情:
if (variable == a - z) {printf("You entered a letter! You must enter a number!");} else (//do something}
我想检查以确保用户没有输入字母,而是输入了一个数字。想知道是否有一种简单的方法可以在不手动输入字母表的每个字母的情况下提取每个字母:)
有没有一种简单的方法可以调用 C 脚本来查看用户是否输入了英文字母表中的字母?我在想这样的事情:
if (variable == a - z) {printf("You entered a letter! You must enter a number!");} else (//do something}
我想检查以确保用户没有输入字母,而是输入了一个数字。想知道是否有一种简单的方法可以在不手动输入字母表的每个字母的情况下提取每个字母:)
最好测试十进制数字本身而不是字母。 是数字。
#include <ctype.h>
if(isdigit(variable))
{
//valid input
}
else
{
//invalid input
}
#include <ctype.h>
if (isalpha(variable)) { ... }
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 <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#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;
* e.g., 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;
}