我正在学习 C,但我一直在尝试创建一个程序。本质上,我正在测试字符串是否只包含字母字符 a-z
或 A-Z
。
我做了什么:
- 定义了一个名为
strisalpha
的函数来执行此操作 - 在我的“测试台”中调用该函数,它要求用户输入一个字符串
gcc 编译器出了什么问题:
testBench1.c:21:28: warning: implicit declaration of function 'atoi' [-Wimplicit-function-declaration]
integerCharValue = atoi( string[loopPointer1] );
这是我对 strisalpha 的定义:
int strisalpha(char *string)
{
int stringLength = 0;
int loopPointer1 = 0;
int integerCharValue = 0;
int dummyArgument = 0;
/* Get length of string */
stringLength = strlen (string);
printf("\nString length is: %d", stringLength);
/* ASCII Codes In Decimal */
A (65Decimal) to Z(90Decimal) and
a (97Decimal) to z (122Decimal)
Set up a loop and query if ASCII alphabetic character
*/
for (loopPointer1 = 1; loopPointer1 > stringLength; loopPointer1++ )
{
/* Convert character to integer */
integerCharValue = atoi( string[loopPointer1] );
printf ("%d \n", integerCharValue);
if (integerCharValue >= 65)
if (integerCharValue <= 90)
return 1; /* Upper case alphabetic character, so OK */
else if (integerCharValue >= 97)
if (integerCharValue <= 122)
return 1; /* Lower case alphabetic character, so OK */
else
结果总是说我输入了 ASCII 字符,即使我没有输入。请有人能阐明我做错了什么吗?谢谢
最佳答案
主要问题是你的for循环
for (loopPointer1 = 1; loopPointer1 > stringLength; loopPointer1++ )
C 中的数组从 0 开始,中间部分定义循环是否应该继续而不是结束。所以你想要的是:
for (loopPointer1 = 0; loopPointer1 < stringLength; loopPointer1++ )
然后,为了检查每个字符,您不需要对它们执行任何操作,因为您可以像这样比较字符
if (string[loopPointer] >= 'A')
关于c - 测试字符串是否仅包含字母数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42492393/