通过一段简单的代码来认识fgets()函数,fputs()函数的用法
#include <stdio.h>
#define STLEN 14//定义了输入的长度
int main(void){
char words[STLEN];
puts("Enter a string,please");
fgets(words, STLEN, stdin);
printf("your string twice(puts(),then fputs()):\n");
puts(words);
fputs(words, stdout);
puts("Enter another string,please");
fgets(words, STLEN, stdin);
printf("your string twice (puts,then fputs()):\n");
puts(words);
fputs(words, stdout);
puts("Done.");
return 0;
}
运行结果:
第一行输入,I will help,比fgets()读入的整行输入短,因此,I will help\n\0被存储在数组中。所以当puts()显示该字符串时又在末尾添加了换行符,因此I will help后面有一行空行。因为fputs()不在字符串末尾添加换行符,所以并未打印出空行。
第二行输入,I will help you,超出了大小的限制,所以fgets()只读入了13个字符。再次提醒,puts()函数会在末尾添加一个换行符,而fputs()不会这样做!