"%d"
및 " %d"
은 OP의 추론에 따라 동일합니다.
확실히 예상 숫자 입력은 "123"
및 " 456"
과 동일합니다. 남아있는 고려 사항은 FILE
포인터가 "abc"
대 " xyz"
과 같이 실패 할 때 어디에 있습니까? "%d"
그 자체로, 첫 번째은 공백을 소비합니다. 차이는 없습니다.
...A 변환 사양은 다음 단계에서 실행됩니다 C11dr §7.21.6.2 7
입력 공백 문자가 ... 건너 뜁니다, 사양은 [
, c
, 또는 n
지정자를 포함하지 않는. 8
§7.21.6.2 다음 ("%d"
용) 숫자 입력 텍스트를 변환 발생한다.
아래 코드는 동등 함을 보여줍니다.
void next_testi(const char *s, const char *fmt, const char *pad) {
rewind(stdin);
int i = 0;
int count = scanf(fmt, &i);
int next = fgetc(stdin);
printf("format:\"%s\",%s count:%2d, i:%2d, next:%2d, text:\"%s\"\n", //
fmt, pad, count, i, next, s);
}
void next_test(const char *s) {
FILE *fout = fopen("test.txt", "w");
fputs(s, fout);
fclose(fout);
freopen("test.txt", "r", stdin);
next_testi(s, "%d", " ");
next_testi(s, " %d", "");
puts("");
}
int main() {
next_test("3");
next_test(" 4");
next_test("");
next_test(" ");
next_test("+");
next_test(" -");
next_test("X");
next_test(" Y");
}
출력
format:"%d", count: 1, i: 3, next:-1, text:"3" // scanf() return value 1:success
format:" %d", count: 1, i: 3, next:-1, text:"3"
format:"%d", count: 1, i: 4, next:-1, text:" 4"
format:" %d", count: 1, i: 4, next:-1, text:" 4"
format:"%d", count:-1, i: 0, next:-1, text:"" // scanf() return value EOF, next is EOF
format:" %d", count:-1, i: 0, next:-1, text:""
format:"%d", count:-1, i: 0, next:-1, text:" "
format:" %d", count:-1, i: 0, next:-1, text:" "
format:"%d", count: 0, i: 0, next:43, text:"+" // scanf() return value 0
format:" %d", count: 0, i: 0, next:43, text:"+"
format:"%d", count: 0, i: 0, next:45, text:" -"
format:" %d", count: 0, i: 0, next:45, text:" -"
format:"%d", count: 0, i: 0, next:88, text:"X"
format:" %d", count: 0, i: 0, next:88, text:"X"
format:"%d", count: 0, i: 0, next:89, text:" Y"
format:" %d", count: 0, i: 0, next:89, text:" Y"
[scanf와 상이한 포맷의 차이]의 가능한 복제 (http://stackoverflow.com/questions/38126126/difference-between-different-scanf-formats) – rsp
@rsp , 정확히. 나는 이미 답을 주었다. 또한 Chegg 솔루션과 내 솔루션을 비교하고 있습니다. 또한 숙제 문제가 아닙니다. – CroCo
@CroCo 목록 서식을 터프하게 읽는 텍스트 조각으로 되돌릴 수있는 이유는 무엇입니까? –