티스토리 뷰

Step 1.

 #include <stdio.h>
void main(){
 char a, b, c;
 printf("Enter a character.\n");
 scanf("%c", &a);
 printf("\nThe character entered was %c.\n", a);
 printf("Enter three more characters.\n");
 scanf("%c%c%c", &a, &b, &c);
 printf("\nThe characters entered were %c%c%c.\n", a, b, c);
}

 문제

Explain the results obtained in Step1.

In particular, what was left in the input stream after executing scanf the first time?


 프로그램을 실행시키기 전에는

a가 출력된 후 abc.가 출력되어야 한다고 생각했는데

어째서 실행해보면

a출력후 ab.만 출력되는 걸까

=============================================================

/* 키보드로 입력한 값을 scanf가 바로 읽는 것은 아닙니다.

   키보드로 입력한 값이 버퍼라는 메모리에 저장되고

   scanf함수는 그 버퍼를 읽어서 처리하게 됩니다.

   그래서 발생한 문제입니다. 아래를 보시죠~ */


#include <stdio.h>


void main()

{

    char a, b, c;


    printf("Enter a character.\n");


    scanf("%c", &a);

/* 위 부분에서 "a"를 입력하고 엔터를 누르면 입력버퍼에는

아래처럼 입력됩니다.

a
 \n
 ...
 

여기서 scanf에 의해 첫 부분의 한 글자 즉 'a'만 버퍼에서 빠져나가

a변수에 저장됩니다. 그러면 입력버퍼에는

\n
 ...
 

개행문자 만이 남게됩니다.

*/

    printf("\nThe character entered was %c.\n", a);

    printf("Enter three more characters.\n");


    scanf("%c%c%c", &a, &b, &c);

 /*

   위 scanf에서 "abc"를 입력받고 엔터를 누르면 입력버퍼에는

\n
 a
 b
 c
 \n
 ...
 

  이런 상태로 저장이 되어버립니다.

맨 위에서 입력되었던 개행문자가 아직 버퍼에 남아있네요.

개행문자도 문자이므로 scanf함수에서 문자입력에 영향을 줍니다.

변수 a, b, c에 버퍼 첫부분부터 차례로 꺼내서 저장하면

a변수에는 '개행문자'가, b변수에는 'a'가, c변수에는 'b'가 들어갑니다.

그래서 출력해보면 한줄 바꾸고 ab가 출력됩니다.

*/

   printf("\nThe characters entered were %c%c%c.\n", a, b, c);

}


이 문제를 해결하려면 위의 scanf함수 사용후 입력버퍼를 비우고

다시 버퍼를 쓰게 만들면 됩니다.

C에서는 fflush함수를 이용하여 버퍼를 비웁니다.

아래는 고친 소스입니다.


#include <stdio.h>


void main()

{

    char a, b, c;


    printf("Enter a character.\n");

    scanf("%c", &a);

    fflush(stdin); /* 입력버퍼를 비웁니다. */

    printf("\nThe character entered was %c.\n", a);

    printf("Enter three more characters.\n");

    scanf("%c%c%c", &a, &b, &c);

    printf("\nThe characters entered were %c%c%c.\n", a, b, c);

}

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함