C언어 stdin 버퍼 비우기

1 개념[ | ]

C언어, stdin 버퍼 비우기
C Language, stdin buffer clearing

2 예시[ | ]

버퍼를 비우지 않는 경우
#include <stdio.h>
int main() {
	int a;
	char c;
	scanf("%d", &a);
	printf("%d\n", a);	
	scanf("%c", &c);
	printf("%c\n", c);
	return 0;
}
→ 프로그래머는 a 변수에 숫자를 받고 c 변수에 문자를 받으려고 한 것이다. 하지만 실제 프로그램을 실행하면 c 변수를 입력하기도 전에 종료되어 버린다. 숫자를 입력하면서 친 엔터키로 개행문자('\n')가 발생하고 c 변수가 채워진 것이다.
버퍼를 비우는 경우
#include <stdio.h>
void clear_stdin() {
	int ch;
	while ((ch = getchar()) != EOF && ch != '\n') {};
}
int main() {
	int a;
	char c;
	scanf("%d", &a);
	printf("%d\n", a);	
	clear_stdin();
	scanf("%c", &c);
	printf("%c\n", c);
	return 0;
}
→ 추가 작성한 함수 clear_stdin()를 실행하면 stdin의 개행문자가 제거되어 의도한대로 동작한다.

3 fflush[ | ]

  • 참고로 윈도우에서는 'fflush()'라는 stdin의 버퍼를 비워주는 함수를 쓸 수 있는데, 표준이 아니라서 리눅스 환경에서는 동작하지 않는다.
  • 때문에 위 예시에는 별도의 함수를 만들어 사용하였다.

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}