#include <stdio.h>
char *fgets(char *s, int size, FILE *stream);
功能:从stream指定的文件内读入字符,保存到s所指定的内存空间,直到出现换行字符、读到文件结尾或是已读了size - 1个字符为止,最后会自动加上字符 '\0' 作为字符串结束。
参数:
- s:字符串
- size:指定最大读取字符串的长度(size - 1)
- stream:文件指针,如果读键盘输入的字符串,固定写为stdin
返回值:
- 成功:成功读取的字符串
- 读到文件尾或出错: NULL
fgets()在读取一个用户通过键盘输入的字符串的时候,同时把用户输入的回车也做为字符串的一部分。
通过scanf和gets输入一个字符串的时候,不包含结尾的“\n”,但通过fgets结尾多了“\n”。
fgets()函数是安全的,不存在缓冲区溢出的问题。
案例
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int main(void)
{
// fgets()
// 可以接受空格
// 将用户输入的回车也会算作为字符串的一部分
// 获取字符串少于元素个数会有\n、大于等于时没有\n
// fgets(存放数组, 数组大小, 默认指针);
char ch2[10];
fgets(ch2, sizeof(ch2), stdin);
printf("%s", ch1);
return 0;
}
fgets 使用案例