728x90
반응형
8.4 사용자 인터페이스는 친절하게
- 문자를 계속 입력받으며 횟수를 세고 n을 입력하면 종료하는 프로그램
#include <stdio.h>
#pragma warning (disable:4996)
main()
{
int count = 0;
while (1) {
printf("Current count is %d. Continue? (y/n)\n", count);
if (getchar() == 'n')
break;
while (getchar() != '\n') // 버퍼에서 첫번째 입력한 문자만 남김
continue;
count++;
}
}
Output :
Current count is 0. Continue? (y/n)
(a 입력)
Current count is 1. Continue? (y/n)
(b 입력)
Current count is 2. Continue? (y/n)
(c 입력)
Current count is 3. Continue? (y/n)
(n 입력)
종료
- 사용자는 우리가 예측한대로 프로그램을 사용하지 않음
- 더 이용하기 편리하게 코딩을 해야 함
#include <stdio.h>
#pragma warning (disable:4996)
main()
{
int count = 0;
while (1) {
printf("Current count is %d. Continue? (y/n)\n", count);
int c = getchar(); // 입력받은 문자 저장
if (c == 'n')
break;
else if (c == 'y')
count++;
else
printf("Please input y or n\n");// 사용자가 이용하기 편하게 해줌
while (getchar() != '\n') // 버퍼에서 첫번째 글자만 남김
continue;
}
}
결과는 위와 동일
8.5 숫자와 문자를 섞어서 입력받기
- 문자 하나와 숫자 두개를 입력받아 입력받은 문자를 첫번째 숫자만큼의 행, 두번째 숫자만큼의 열로 출력하는 프로그램
#include <stdio.h>
#pragma warning (disable:4996)
void display(char cr, int lines, int width);
main()
{
char c;
int rows, cols;
while (1) {
scanf("%c %d %d", &c, &rows, &cols);
while (getchar() != '\n')
continue;
display(c, rows, cols);
if (c == '\n')
break;
}
}
void display(char cr, int lines, int width) {
for (int i = 0; i < lines; i++) {
for (int j = 0; j < width; j++)
putchar(cr);
putchar('\n');
}
}
Output :
(A 2 3 입력)
AAA
AAA
(* 3 2 입력)
**
**
**
( 엔터 입력)
(1 3 입력)
종료
위의 코드는 엔터를 입력하고 숫자 두개를 입력한다음 다시 엔터를 입력해야 종료됨 : 매끄럽게 종료되지 않음
#include <stdio.h>
#pragma warning (disable:4996)
void display(char cr, int lines, int width);
main()
{
char c;
int rows, cols;
printf("Input one character and two integers : \n");
while ((c = getchar()) != '\n') {
scanf("%d %d", &rows, &cols);
while (getchar() != '\n')
continue;
display(c, rows, cols);
printf("Input another character and two integers : \n");
printf("Press Enter to quit");
}
}
void display(char cr, int lines, int width) {
for (int i = 0; i < lines; i++) {
for (int j = 0; j < width; j++)
putchar(cr);
putchar('\n');
}
}
Output :
Input one character and two integers :
* 3 2
**
**
**
Input another character and two integers :
Press Enter to quit
(엔터 입력)
종료
getchar를 사용하여 해결
https://www.inflearn.com/course/following-c/dashboard
홍정모의 따라하며 배우는 C언어 - 인프런 | 강의
'따배씨++'의 성원에 힘입어 새롭게 개발된 C 언어로 시작하는 프로그래밍 입문 강의입니다. '따배씨'와 함께 프로그래밍 인생을 업그레이드 해보세요., - 강의 소개 | 인프런...
www.inflearn.com
728x90
반응형
'Study_C, C++ > 홍정모의 따라하며 배우는 C언어' 카테고리의 다른 글
[홍정모의 따라하며 배우는 C언어] 8.7 입력 스트림과 숫자 (0) | 2022.03.07 |
---|---|
[홍정모의 따라하며 배우는 C언어] 8.6 입력 확인하기 (0) | 2022.03.06 |
[홍정모의 따라하며 배우는 C언어] 8.1 입출력 버퍼 ~ 8.3 입출력 방향 재지정 (0) | 2022.02.08 |
[홍정모의 따라하며 배우는 C언어] 7.11 최대, 최소, 평균 구하기 예제 ~ 7.13 goto를 피하는 방법 (0) | 2022.02.05 |
[홍정모의 따라하며 배우는 C언어] 7.8 단어 세기 예제 ~ 7.10 루프 도우미 continue와 break (0) | 2022.01.28 |