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()
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()
:
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
を使用する習慣を身につけてください。
ありがとう!良い説明 –
fgets
は、末尾に'\n'
の文字列を返します。gets
ではなく、文字列を返します。 gets()
man pageから
:
gets()
機能は、改行文字(もしあれば)は、文字列に格納されていないことを除いて、無限n
とstdin
のstream
とfgets()
と等価です。gets
/fgets
manページから
[get 'manページ](http://linux.die.net/man/3/gets):" gets()を使わないでください。多くのキャラクタgets()は読み込みを行い、gets()はバッファの末尾を越えて文字を格納し続けるため、非常に危険です。代わりにfgets()を使用してください。 –