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

、I入力 "ABCD" 2回、 を取得し、私が得た結果は次のとおりです。4,5 理由は何ですか?Cは、()、実行後のfgets()

+2

[get 'manページ](http://linux.die.net/man/3/gets):" gets()を使わないでください。多くのキャラクタgets()は読み込みを行い、gets()はバッファの末尾を越えて文字を格納し続けるため、非常に危険です。代わりにfgets()を使用してください。 –

答えて

4

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ません。 getsを使用している場合、バッファオーバーフローを防ぐことは不可能であるため、常にfgetsを使用する習慣を身につけてください。

+0

ありがとう!良い説明 –

2

fgetsは、末尾に'\n'の文字列を返します。getsではなく、文字列を返します。 gets() man pageから

+0

他の方法で、私は思います。 –

+0

あなたはそうです。編集されました。 – Marii

+0

正反対です。私は考えています –

0

gets()機能は、改行文字(もしあれば)は、文字列に格納されていないことを除いて、無限nstdinstreamfgets()と等価です。 gets/fgets manページから

関連する問題