2011-01-26 2 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"두 번, 내가 얻은 결과는 다음과 같습니다 4,5 는 이유입니까?C 가져옵니다()는 fgets()

+2

[gets'맨 페이지에서] (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() man page 가입일

+0

다른 방법으로 생각합니다. –

+0

네 말이 맞아. 편집 됨. – Marii

+0

정반대로 .. 생각해. –

0

:

gets() 함수 무한 nfgets()와 동등하고, 개행 문자 (있는 경우) 문자열에 저장되어 있지 않은 것을 제외 stdinstream. gets/fgets 사람 페이지에서

관련 문제