我正在使用C,我需要检查用户输入的第二个命令行参数argv1是否只由字母字符组成,如果不是,则执行else循环中的操作。我使用了is alpha函数,但是当我编译和运行程序时,不管我的第二个命令行参数是什么(按字母或其他顺序),它总是执行"else循环“。我该如何解决这个问题?
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
int a = argc;
if (a != 2)
{
return 1;
}
string b = argv [1];
int c = strlen(b);
string m;
for (int i = 0; i < c; i++)
{
if (isalpha(b[c]))
{
m = GetString();
}
else
{
printf("Please provide a valid keyword\n");
return 1;
}
}
} 发布于 2015-07-26 07:08:33
尝试替换
if (isalpha(b[c]))使用
if (isalpha(b[i]))目前,您正在检查索引处的元素,这是在循环的每次迭代中执行strlen(b)的结果。因为在C中数组索引是以零为基础的,所以b[strlen(b)]引用了空终止符'\0'。
参考下面的Keith Thompson注释和对this question的回答,您实际上应该将传递给isalpha的值转换为unsigned char,以确保未定义的行为不会被调用。
因此,您应该将代码更改为
if (isalpha((unsigned char)b[i]))确保没有UB
发布于 2015-07-26 20:12:40
使用isalpha(b[i])代替isalpha(b[c]),如下所示:
if (isalpha(b[i]))
{
m = GetString();
}https://stackoverflow.com/questions/31631971
复制相似问题