fgets函数原型:char *fgets(char *buf, int bufsize, FILE *stream);
fgets函数相当于是gets函数的改进版。它没有gets函数存在的安全隐患,当然使用起来要相对麻烦一点。
函数的第二位参数需要指定读入字符的最大数量,并且如果该参数是n,那么能读入的字符数是n-1或者遇到换行符为止。
函数的第三位参数需要指定要读入的文件。若是从键盘输入数据,以stdin作为参数。
注意:当遇到换行符时,gets与fgets的处理方式不同。gets()会丢弃换行符,而fgets则会把换行符储存到字符串中。
fputs函数原型:int fputs(const char *str, FILE *stream);
fputs函数用法与puts函数基本一致。不过也有不同之处,puts函数会在待输出的字符串末尾添加一个换行符,而fputs函数不会。与fgets函数相似,fputs函数第二位参数需要指定写入文件,在显示器上显示,应用stdout作为该参数。
下面看两段代码
#include<stdio.h>
#define STLEN 10
int main()
{
charwords[STLEN];
puts("输入字符串:");
while(fgets(words, STLEN, stdin) != NULL && words[0] != '\n')
fputs(words,stdout);
return0;
}
输出结果如下(粗体表示从键盘输入):
输入字符串:
hello everybody
hello everybody
I am XN and i am a student
I am XN and i am a student
college
college
student
student
此程序中,STLEN虽然被设置为10,但是输出结果却好像并没有受到限制。其实不是这样。本质上是因为看似输出的是一句话,但事实上却是分成了几段输出的。例如 hello everybody,第一次输出hello eve,第二次输出rybody\n
#include<stdio.h>
#define STLEN 10
int main()
{
charwords[STLEN];
inti;
charx;
puts("输入字符串:");
while(fgets(words, STLEN, stdin) != NULL && words[0] != '\n')
{
i= 0;
while((words[i] != '\n' && words[i] != '\0'))
i++;
if(words[i] == '\n')
words[i]= '\0';
else
while((x=getchar()) != '\n')
continue;
puts(words);
}
return0;
}
输出结果如下(粗体表示从键盘输入) :
输入字符串:
hello everybody
hello eve
I am XN and i am a student
I am XN a
college
college
student
student
下面一段代码是上一段的基础上改来的。目的在于处理掉换行符。

这段代码的意义是,遍历字符串,知道遇到换行符或空字符。遇到换行符,将其替换为空字符。遇到空字符,丢弃输入行的剩余字符。
代码和解释来自《C Primer Plus第六版》,略有修改。
新来乍到,第一次写博客。不怎么懂,主要是为了自己学习以及记录我自己认为有重点的东西。若是大家有什么疑惑或者建议,欢迎提出来。