fgets函数的声明如下:

char *fgets(char *s, int size, FILE *stream);

s表示待接收字符串的缓冲区,size为最大大小,stream为读取的数据流。

对于数据的读取来说,函数实际最多读到size - 1个字节,如果读取的数据比这个长,会自动截断,保证在最后以\0结尾,要注意的是读取字符时会把\n也读进来

对于以下代码:

#include <stdio.h>
#include <string.h>

const int BUFF_SIZE = 10;

int main() {
    char buf[BUFF_SIZE];
    int len;

    while(fgets(buf, BUFF_SIZE, stdin) != 0) {
        printf("%s\n", buf);
    }

    return 0;
}

编译:

gcc main.cpp -o app

运行:

$ ./app
hello # 输入hello,实际存到buf中的为hello再加上''\n''。
hello
 # 输出上面的hello后还会输出一个\n

此时可采取的应对方法为:

// ...
while(fgets(buf, BUFF_SIZE, stdin) != 0) {
    len = strlen(buf); // 长度会算上\n字符
    if (len == 1) // 如果输入为空,跳过
        continue;
    if (buf[len - 1] == ''\n'') { // 最后一个字符为\n,把它置零
        buf[len - 1] = 0;
    }
    printf("%s\n", buf);
}
// ...
最后修改:2018 年 12 月 16 日
如果觉得我的文章对你有用,请随意赞赏