C언어 기초: 전처리와 입출력

김영채 (Kevin)·2020년 3월 3일
0

C언어

목록 보기
2/23
post-thumbnail

전처리 지시자 (Preprocess Directives)

-#include, #define 과 같이 #으로 시작

-세미콜론 ; 이 없음

#include <stdio.h>  // 헤더 파일

#define PI 3.14  // 매크로 상수
#define PRT printf("종료\n")

ex)

#include <stdio.h>
#define KPOP 5000000
#define PI 3.14
#define PRT printf("매크로 상수 예제 종료\n")

int main(void)
{
	double radius = 2.83;
	
	printf("한국인구: %d명\n", KPOP);
	printf("원 면적: %f\n", radius * radius * PI);
	PRT; // 이렇게 작성하면 바로 "매크로 상수 예제 종료"가 출력됨

	return 0;

}

인자를 사용하는 매크로

#define PI 3.141592
#define VOLUME(r)  (4 * PI * CUBE(r) / 3) //구의 체적을 구하는 매크로
#define SQUARE(x)  ( (x) * (x) )  //인자 x의 제곱을 구하는 매크로
#define CUBE(x)  ( SQUARE(x) * (x) ) //인자 x의 세제곱 구하는 매크로
#define MULT(x,y)  ( (x) * (y) ) //인자 x,y의 곱 구하는 매크로

출력 폭 지정

기본 format: %[+|-][전체폭],[소수점이하폭]{d|i|f}

int n = 255;
double f = 3.141592;

printf("%10d\n",n);   //폭이 10이며 우측정렬로 출력
printf("%+10d\n",n);  //+에 의해 부로 +가 출력
printf("%-10d\n",n);  //-에 의해 좌측정렬로 출력
printf("%f\n",n);     //실수는 소수점 이하 6자리까지 출력
printf("%10f\n",n);   //폭이 10이며 소수점 이하 4자리까지 우측정렬로 출력
printf("%+10.4f\n",n);//+에 의해 부로 +가 출력

형식 지정자 정리: %[flags][width].[precision]{h|l|ll}type // ll 은 long long을 의미


입력 함수 scanf()

기본 구조:

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

예제:

int year = 0;
printf("당신의 입학년도는? ");
scanf("%d", &year);
printf("입학년도: %d\n", year);

int month, day;
printf("당신의 생년월일은? ");
scanf("%d - %d %d", &year, &month, &day);    // - 는 구분자(separator)이다.
printf("생년월일: %d-%d-%d\n", year, month, day);

실수와 문자의 입력: %f, %lf, %c

float pi; char ch1, ch2;
printf("원주율을 입력하세요.\n");
scanf("%f", &pi);  // 실수 입력을 받음
printf("%f\n, pi);


//버퍼 해결 방법 1
printf("구분자를 공백으로 두 문자를 입력하세요.\n");
scanf(" %c %c", &ch1, &ch2);   //%c 앞에 공백을 둬야 버퍼 처리 가능
printf("ch1=%c chd2=%c\n", ch1, ch2);

//버퍼 해결 방법 2
scanf(%f", &pi);
fflush(stdin); //입력 버퍼를 모두 비움
scanf("%c", &ch);

함수 getchar()와 putchar()

  • 함수 getchar()는 인자 없이 함수를 호출하며 입력된 문자값을 자료형 char나 정수형으로 선언된 변수에 저장할 수 있다.

  • 함수 호출 putchar('a')는 인자인 'a'를 출력하는 함수로 사용한다.

    char a = '\0';
    puts("문자 하나 입력: ");
    a = getchar();
    putchar(a); putchar("\n");

profile
맛있는 iOS 프로그래밍

0개의 댓글