fgets
函数的声明如下:
1 |
char *fgets(char *s, int size, FILE *stream); |
s
表示待接收字符串的缓冲区,size
为最大大小,stream
为读取的数据流。
对于数据的读取来说,函数实际最多读到size - 1
个字节,如果读取的数据比这个长,会自动截断,保证在最后以\0
结尾,要注意的是读取字符时会把\n也读进来。
对于以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#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; } |
编译:
1 |
gcc main.cpp -o app |
运行:
1 2 3 4 |
$ ./app hello # 输入hello,实际存到buf中的为hello再加上'\n'。 hello # 输出上面的hello后还会输出一个\n |
此时可采取的应对方法为:
1 2 3 4 5 6 7 8 9 10 11 |
// ... 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); } // ... |
评论