본문 바로가기

C-Language/Format Specifiers

C Format Specifiers

C 프로그래밍, 형식화 출력(format output)을 위한 형식 지정자(format specifiers)


  • %c char single character
  • %d (%i) int signed integer
  • %e (%E) float or double exponential format
  • %f float or double signed decimal
  • %g (%G) float or double use %f or %e as required
  • %o int unsigned octal value
  • %p pointer address stored in pointer
  • %s array of char sequence of characters
  • %u int unsigned decimal
  • %x (%X) int unsigned hex value
  • %% '%' itself


#include <stdio.h>

int main()
{
	int a, b;
	float c, d;

	a = 15;
	b = a / 2;

	//형식화 출력(formatted output)시의 형식 지정자(format specifiers)
	printf("%d \n", b);		//7
	printf("%3d \n", b);		//  7
	printf("%03d \n", b);		//007

	c = 15.3;
	d = c / 3;	// 5.1
	
	// 5.1을 출력할 때의 형식지정자
	// 예) "%05.2f" : 최소 5개의 자리에 소수점 이하는 2자리를 배정. 빈자리는 0으로 채움
	// 소수점도 한자리를 차지함
	printf("%.2f \n", d);		//5.10
	printf("%1.2f \n", d);	//5.10
	printf("%2.2f \n", d);	//5.10
	printf("%3.2f \n", d);	//5.10
	printf("%4.2f \n", d);	//5.10
	printf("%5.2f \n", d);	// 5.10
	printf("%05.2f \n", d);	//05.10

	printf("%05x \n", 255);	//000ff
	printf("%05o \n", 255);	//00377

	printf("%% \n");			// %
	printf("10%% \n");		// 10%

	printf("%5s \n", "Hello, World"); //최소 5자의 공간 확보
	printf("%20s \n", "Hello, World");//최소 20자 공간에 우정렬. 왼쪽 빈곳은 space
	printf("%.10s \n", "Hello, World");// 10자만
	printf("%-20s %s \n", "Hello, World","|"); //최소 20자 공간에 좌정렬. 오른쪽 빈곳에 space
	printf("%20.10s \n", "Hello, World");//최소20자 공간 우정렬. 10자만 출력
	printf("%-20.5s %s \n", "Hello, World","|");//최소20자공간 좌정렬. 5자만 출력
	return 0;
}