我創建了一個接受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