Desc :

 

fflush() --> while (getchar() != '\n'); 변경

 

getchar(): 읽어들인 값을 반환하는 함수

이를 이용해서 줄바꿈 문자 즉, '\n'을 읽어들일 때까지 계속해서 반복하다가 '\n'을 읽어들이면 while문을 빠져나오게 하는 겁니다. 이렇게 하면 위에서 fflush(stdin)를 사용함으로써 원했던 결과와 똑같은 결과를 얻을 수 있습니다.

 

fflush() 함수가 비우는 건 입력 버퍼가 아닌 출력 버퍼입니다. 그런데 위 프로그램에서는 stdin 즉, 표준 입력 스트림을 매개변수로 전달함으로써 입력 버퍼를 비우려고 하고 있습니다.

 

"저렇게 해봤는데 아무 문제 없이 잘 되던데요?"라고 묻는 분이 있을 겁니다. fflush() 함수의 매개변수로 입력 스트림을 전달하는 것은 정의되지 않은 방법입니다. 즉, 어떻게 작동할지 정의돼 있지 않기 때문에 그 누구도 결과를 예측할 수 없고, 경우에 따라 치명적인 결과를 초래할 수도 있습니다. 물론 저렇게 사용하더라도 원하는 방향대로 잘 작동할 수도 있습니다. 하지만 이는 어디까지나 가능성입니다. 

 

출처:https://8ublictip.tistory.com/6

 


Source Code :

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <memory.h>

void clearInputBuffer()
{
	// 입력 버퍼에서 문자를 계속 꺼내고 \n를 꺼내면 반복을 중단
	while (getchar() != '\n');
}

void main()
{
	int com[3] = { 0, };
	int gamer[3] = { 0, };
	int guess[10] = { 0, };
	int count = 0, i = 0;
	int strike = 0, ball = 0;
	int yesno = 0;

	srand(time(NULL));

	puts("야구게임을 시작합니다.");

	while (1)
	{
		com[0] = rand() % 10;
		com[1] = rand() % 10;
		com[2] = rand() % 10;
		count = 1;

		if (com[0] == com[1] || com[0] == com[2] || com[1] == com[2]) continue;

		puts("\n숫자 0~9를 공백으로 분리하여 3개 입력하고 엔터키를 치세요!");

		memset(guess, 0, sizeof(guess));

		while (1)
		{
			strike = 0;
			ball = 0;

			for (i = 0; i < 10; i++)
			{
				printf("%d ", i);
			}
			printf("\n");
			for (i = 0; i < 10; i++)
			{
				printf("%d ", guess[i]);
			}

			printf("\n3개의 숫자[0~9]를 입력하세요:");

			scanf("%d %d %d", &gamer[0], &gamer[1], &gamer[2]);

			if (com[0] == gamer[0]) strike++;
			else if (com[0] == gamer[1] || com[0] == gamer[2]) ball++;

			if (com[1] == gamer[1]) strike++;
			else if (com[1] == gamer[0] || com[1] == gamer[2]) ball++;

			if (com[2] == gamer[2]) strike++;
			else if (com[2] == gamer[0] || com[2] == gamer[1]) ball++;

			if (gamer[0] > 9 || gamer[1] > 9 || gamer[2] > 9)
			{
				puts("입력한 숫자가 너무 큽니다. 0~9를 입력하세요");
				continue;
			}

			guess[gamer[0]] = 1;
			guess[gamer[1]] = 1;
			guess[gamer[2]] = 1;

			printf("[%2d회] %d스트라이크 %d볼 \n\n", count, strike, ball);
			if (strike == 3) break;
			count++;
		}
		
		printf("게임을 계속하시겠습니까?(y/n)>>"); 
	
		clearInputBuffer();

		scanf("%c", &yesno);

		
		if (yesno == 'N' || yesno == 'n')
		{
			break;
		}
	}
}

 


Result :

+ Recent posts