[38일차](홍정모의따배c)메뉴만들기 예제
*본 강의수기는 교수님의 모든 ppt나 코드 화면을 붙인게 아닙니다. 따로 출처 표시나 과제표시
안한 모든 코드와 사진자료의 출처는 본 강의의 교수님 입니다.
정리는 다시한번 제가 보기위함과 어떤강의인지 알려드리는 것이고
제가 적은건 이해를 돕기 위한 부연설명과 제가 이해한 몇개의 중심적인 내용이 다소
생략이 되었습니다. 이 수기를 통해 공부하려 하지말고 흥미로운 내용이라면
'인프런- 홍정모의 따라하며 배우는c' 과정을 수강하시길 바랍니다.
- 문제
위와같이 각 메뉴들을 구현하고 각메뉴에 해당하는 기능들을 구현해라
- 내코드
#include <stdio.h>
int main()
{
char c;
while(1)
{
printf("Enter the letter of your choice\n");
printf("a. avengers b. beep\nc. count q. quit\n");
c = getchar();
if (c == 'a')
{
printf("Avengers assemble\n");
}
if (c == 'b')
{
printf("\a");
}
if (c == 'c')
{
int i, output = 0;
while(1)
{
printf("Enter an integer :\n");
scanf("%i", &i);
while(output < i)
{
output++;
printf("%i\n", output);
}
break;
}
}
if (c == 'q')
{
break;
}
}
printf("Hasta la vista\n");
return 0;
}
while문이 무한하게 반복하게 하고
메뉴마다 if문을 넣거나
필요할땐 while문을 더 넣었다.
그런데
메뉴를 하나 입력하면 정상적으로
그 기능이 작동하긴 하지만
메뉴를 고르라는 선택문이 두번뜬다.
이유를 알았는게
a를 누르고 엔터를 누르면서
' \n ' 도 같이 버퍼에 저장되는것이었다.
그래서 메뉴선택문이 두번뜬다.
해결방법이 없을까?
좋은 묘수가 떠올랐다
c를 getchar로 받지말고 scanf로 받자. 그러면 굳이 버퍼에 \n이 담기지않을것이다.
그래도 두번뜬다 ㄱ-
또하나 생각한건
반복문밖에서 입출력을 한번 먼저해주자
그리고 반복문 끝에 다시 입출력을 한번 더 하자.
그래도 두번뜸..
수많은 if문들을 while에 한번더 가둬볼까..?
if문들을 \n이 아닐때만 반복하게 그안에 가두자!
해결불가 !
교수님께서 예제코드를 주셨다 여기서 한번 더 완성해 보자.
switch와 case의 존재자체를 까먹고있었다.
- 교수님코드
#include <stdio.h>
#include <stdlib.h>
char get_choice(void);
char get_first_char(void);
int get_integer(void);
void count(void);
int main()
{
int user_choice;
while ((user_choice = get_choice()) != 'q')
{
switch (user_choice)
{
case 'a':
printf("Avengers assemble!\n");
break;
case 'b':
putchar('\a');
break;
case 'c':
count();
break;
default :
printf("Error with %d. \n", user_choice);
exit(1);
break;
}
}
return 0;
}
여기서 프로토타입으로 선언된 함수들을 만들자.
- 교수님코드
get_choice함수
char get_choice(void)
{
int user_input;
printf("Enter the letter of your choice:\n");
printf("a. avengers\tb. beep\n");
printf("c. count\tq. quit\n");
user_input = get_first_char();
while (user_input != 'a' && user_input != 'b' && user_input != 'c' && user_input != 'q')
{
printf("Please try again.\n");
user_input = get_first_char();
}
return user_input;
}
user_input을 선언하고
user_input에 get_first_char함수의 값을 대입한다.
메뉴를 제시하고 입력을 받는다
while문을 활용해 입력 유효성 검증또한 받을 수 있다
get_first_char함수
char get_first_char(void)
{
int ch;
ch = getchar();
while (getchar() != '\n')
continue;
return ch;
}
내가겪었던 문제를 해결한다.
엔터를 받지않으면 while문 하나를 만들어 계속돌게한다
continue를 활용해 버퍼에 입력한 문자를 담고 수정할수있게한다.
그리고 ch를 반환한다.
get_integer함수
int get_integer(void)
{
int input;
char c;
while ((scanf("%d",&input)) != 1)
{
while ((c = getchar()) != '\n')
putchar(c);
printf(" is not an integer.\nPlease try again.");
}
return input;
}
input과 c를 선언하고
유효한입력을 하지 않았을 때(scanf로 정수자료형을 받고있기에 정수가 아니면) 첫번째 반복문에서 돌게 한 후
니가 입력한게 정수가 아니라고 알려준다.
count함수
void count(void)
{
int n, i;
printf("Enter an integer:\n");
n = get_integer();
for (i = 1; i <= n; ++i)
printf("%d\n", i);
while (getchar() != '\n')
continue;
}
get_integer로 받은 정수까지의 수를 증가연산으로 카운트해준다.
종합
#include <stdio.h>
#include <stdlib.h>
char get_choice(void);
char get_first_char(void);
int get_integer(void);
void count(void);
int main()
{
int user_choice;
while ((user_choice = get_choice()) != 'q')
{
switch (user_choice)
{
case 'a':
printf("Avengers assemble!\n");
break;
case 'b':
putchar('\a');
break;
case 'c':
count();
break;
default :
printf("Error with %d. \n", user_choice);
exit(1);
break;
}
}
return 0;
}
char get_choice(void)
{
int user_input;
printf("Enter the letter of your choice:\n");
printf("a. avengers\tb. beep\n");
printf("c. count\tq. quit\n");
user_input = get_first_char();
while (user_input != 'a' && user_input != 'b'&& user_input != 'c' && user_input != 'q')
{
printf("Please try again.\n");
user_input = get_first_char();
}
return user_input;
}
char get_first_char(void)
{
int ch;
ch = getchar();
while (getchar() != '\n')
continue;
return ch;
}
int get_integer(void)
{
int input;
char c;
while ((scanf("%d",&input)) != 1)
{
while ((c = getchar()) != '\n')
putchar(c);
printf(" is not an integer.\nPlease try again.");
}
return input;
}
void count(void)
{
int n, i;
printf("Enter an integer:\n");
n = get_integer();
for (i = 1; i <= n; ++i)
printf("%d\n", i);
while (getchar() != '\n')
continue;
}