【发布时间】:2017-02-25 21:25:36
【问题描述】:
我创建了一个接收 char 指针的函数。我首先从 fgets 获取字符串值,我输入的输入是“rwx”。当我输入该值时,它的 strlen 表示它的长度为 2,当我查看 char 数组的第一个索引时,它返回 rw 而不是 r。请问我在遍历字符串时哪里出错了?
我尝试过的:
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。
标签: c