1. 程式人生 > >Linux下gets函式警告

Linux下gets函式警告

由於Linux下的gcc編譯器不支援gets函式,程式編譯過後會出現一個警告,即:“warning: the `gets' function is dangerous and should not be used.

  此時,可以用fgets函式代替,函式在標頭檔案stdio.h中,函式原型:char *fgets(char *buf, int bufsize, FILE *stream),即從檔案結構體指標stream(鍵盤輸入stdin)中讀取資料,每次讀一行,讀取的資料儲存在buf指向的字元陣列中,每次最多讀bufsize-1個字元(第bufsize個字元賦'\0'),多退少不補。但是緩衝區總是以NULL字元結尾,對fgets的下次呼叫會繼續讀該行。

  ps:fgets函式會讀取'\n'(gets不會),因此有時要將最後的回車符換成\0,否則會有差錯。

  1 #include <stdio.h>
  2 
  3 int main()
  4 {
  5     char str[81];
  6     int i, num = 1, word = 0;
  7     char c;
  8 
  9     fgets

(str, 81, stdin);
 10     for (i=0; (c=str[i])!='\0'; i++)
 11     {
 12         if (c==' ')
 13         {
 14             word = 0;
 15         }
 16         else if (word==0)
 17         {
 18             word = 1;
 19             num++;
 20         }
 21     }
 22     printf("There are %d words in the line.\n", num-1
);
 23 
 24     return 0;
 25 }