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第六版》,略有修改。
新來乍到,第一次寫部落格。不怎麼懂,主要是為了自己學習以及記錄我自己認為有重點的東西。若是大家有什麼疑惑或者建議,歡迎提出來。