2011-01-26 55 views
2
char s1[100]; 
char s2[100]; 
gets(s1); 
fgets(s2,sizeof(s2),stdin); 
printf("%d,%d\n",strlen(s1),strlen(s2)); 

運行後,我輸入 「ABCD」 兩次, ,結果我得到的是:4,5 這是爲什麼?C,獲得()與fgets()

+2

從[a`gets`手冊頁](http://linux.die.net/man/3/gets):「千萬不要使用gets()。因爲事先不知道數據是不可能的許多字符gets()會被讀取,並且由於gets()會繼續存儲緩衝區末尾的字符,因此使用它非常危險,已經被用於破壞計算機安全性,請使用fgets()。 – 2011-01-26 22:33:12

回答

4

gets/fgets手冊頁:

The fgets() function reads at most one less than the number of characters 
specified by n from the given stream and stores them in the string s. 
Reading stops when a newline character is found, at end-of-file or error. 
The newline, if any, is retained. If any characters are read and there 
is no error, a `\0' character is appended to end the string. 

The gets() function is equivalent to fgets() with an infinite n and a 
stream of stdin, except that the newline character (if any) is not stored 
in the string. It is the caller's responsibility to ensure that the 
input line, if any, is sufficiently short to fit in the string. 

fgets保持換行符,這是字符數5,但gets沒有。 此外,養成一直使用fgets的習慣,因爲在使用gets時無法防止緩衝區溢出。

2

因爲fgets返回的字符串結尾爲'\n'gets不是。

+0

其他方法,我想。 – 2011-01-26 22:30:56

+0

你說得對。編輯。 – Marii 2011-01-26 22:32:50

0

gets() man page

gets()函數等效於fgets()具有無限n和的stdinstream,不同之處在於換行字符(如果有的話)不存儲在的字符串中。