我创建了一个接受char指针的函数。我首先从fgets获取字符串值,我输入的输入是“rwx”。当我输入该值时,strlen表示它的长度是2,当我查看char数组的第一个索引时,它会返回rw
而不是r
。我可以问一下我在迭代字符串时会出错吗?fgets()读取的字符数比预期的少
我已经试过:
int main()
{
char access[3];
while (ValidateAccess(access))
{
printf("Please enter your access\n");
fgets (access, 3, stdin);
}
return 0;
}
int ValidateAccess(char * access)
{
int length = strlen(access);
int r = 0,w = 0,x = 0,i;
printf("this is the length %d\n", length);
if (length == 0)
return 1;
for(i = 0; i < length; i++)
{
printf("this is the character: %s", &access[i]);
if (strcmp(&access[i], "r") == 0)
r++;
else if (strcmp(&access[i], "w") == 0)
w++;
else if (strcmp(&access[i], "x") == 0)
x++;
}
if (r <=1 && w <= 1 && x <= 1)
return 0;
else
return 1;
}
当程序运行,这是输出
"this is the length 0"
Please enter your access
rwx
this is the length 2
this is the character: rw
最后一个字符是'\ 0'。 – Shravan40