fgets()学习

fgets函数原型:char *fgets(char *s, int n, FILE *stream);
//我们平时可以这么使用:fgets(str, sizeof(str), stdin);
其中str为数组首地址,sizeof(str)为数组大小,stdin表示我们从键盘输入数据。

读取sizeof(srt) - 1 个字符 存到 str 中 ,返回值为字符串str
遇到换行符结束

两种情况:

1,输入字符长度小于 sizeof(srt) - 1, 系统会在末尾加上 \n,然后在 加个结束符 \0

返回字符串长度包含\n ,比输入的多1.

从文件或标准输入接收一串字符,遇到'\n'时结束,把'\n'也作为一个字符接收

2, 输入字符长度大于等于 sizeof(srt) - 1, 系统在末尾加上\0;

返回字符串长度为sizeof(srt) - 1

代码示例:

#include <stdio.h> #include <string.h> #define N 10 int main() {
  //数组空间10.
char s1[N]; fgets(s1, N, stdin); cout << "s1所占空间大小为:"; cout << sizeof(s1) << endl; cout <<"s1 为:"; cout << s1; if(s1[3] == '\n') { // 去掉换行符 cout << "有换行符"<<endl; } if (s1[4] == '\0') { cout << "自动加了结束符"<<endl; } cout << " s1长度:"; cout << strlen(s1) <<endl; return 0
; }

第一种情况


第二种情况

猜你喜欢

转载自www.cnblogs.com/strivingforever/p/8882402.html
今日推荐