繁体   English   中英

fgets()读取的字符少于预期的字符

[英]fgets() reads fewer characters than expected

我创建了一个带有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

man fgets是一本非常有用的书。 让我引用一下:“ fgets()读取的流最多不超过流中字符的大小...”

C中的字符串应以\\0 (零字节)结尾。 当您将access定义为3个元素的数组时,它有一个空间来容纳长度为2的字符串-两个字符加零字节结尾 当您调用fgets表示您有3个字节的空间时,它将读取两个字符,将它们放在前两个字节中,并在第三个字节中以零结尾。

定义具有4个字节的access a,并将4传递给fgets

另外,您要打印的字符串不是char ,因此它将所有内容打印到终止的零字节(这是您看到的rw来源)。 如果要打印单个字符,请在格式字符串中使用%c ,而不要在%s (然后应传递一个字符,而不是指针)。

尝试以下程序,并确保您了解输出。

#include <stdio.h>

int main() {
        char *foo = "barbaz";

        printf("%c\n", foo[2]);
        printf("%s\n", foo + 2);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM