fgets函數(shù)是gets函數(shù)的替代品眷蜓,C11標(biāo)準(zhǔn)已經(jīng)廢除gets函數(shù).
- fgets函數(shù)的第2個(gè)參數(shù), 它指明了讀入字符的最大數(shù)量,一般傳入數(shù)組的長(zhǎng)度,如果該參數(shù)的值是n单山,那么fgets將讀入包括換行符在內(nèi)的n-1個(gè)字符,數(shù)組最后一個(gè)位置會(huì)自動(dòng)存空字符'\0'.
- fget的返回值為一個(gè)char *指針,指向輸入的內(nèi)容第一個(gè)字符
下面回顯程序去掉了fgets讀取的換行符,如果輸入字符過(guò)多則丟棄
#include <stdio.h>
#define STLEN 10
int main(void)
{
char words[STLEN];
int i;
puts("Enter strings (empty line to quit):");
puts("------------------");
while (fgets(words, STLEN, stdin) != NULL
&& words[0] != '\n')
{
i = 0;
while (words[i] != '\n' && words[i] != '\0')
i++;
if (words[i] == '\n')
{
printf("i = %u replace \'\\n\' to \'\\0\' \n",i);
words[i] = '\0';
}
else // must have words[i] == '\0'
{
printf("words[%u] == \'\\0\' \n",i);
while (getchar() != '\n')// 獲取緩沖區(qū)下一個(gè)字符
// continue;//作用是丟棄剩余的字符
puts("continue");
}
// for(int j=0;j<STLEN;j++){
// printf(" words[%d] to int is %u \n",j,words[j]);
// }
puts(words);
puts("------------------");
}
puts("done");
return 0;
}
下面是程序的輸出示例
Enter strings (empty line to quit):
------------------
12345678
words[8] replace '\n' to '\0'
12345678
鍵盤(pán)輸入12345678榨馁,那么包括回車(chē)換行符共向程序緩沖區(qū)輸入了9個(gè)字符:12345678\n,fgets 全部獲得.
則存在數(shù)組中的為10個(gè)字符:12345678\n'\0',然后替換成了12345678'\0''\0'
------------------
123456789
words[9] == '\0'
123456789
輸入123456789\n, 緩沖區(qū)共10個(gè)字符, fgets獲得9個(gè)字符黎休,則存在數(shù)組中的為123456789'\0'
此時(shí)還有個(gè)換行符\n存在緩沖區(qū),由getchar()取出,然后什么都不做進(jìn)入下一輪主循環(huán)
------------------
1234567890
words[9] == '\0'
continue
123456789
輸入1234567890\n, 緩沖區(qū)共11個(gè)字符, fgets獲得9個(gè)字符,則存在數(shù)組中的為123456789'\0'
此時(shí)還有個(gè)0和換行符在緩沖區(qū),getchar()先取出0打印continue然后取出換行符while結(jié)束,進(jìn)入下一輪主循環(huán)
------------------