printf
prints formatted output to stdout.
stdout : 표준출력스트림 ~ 출력될 문자들이 흐른다
콘솔 화면에 연결되어 있음.
Format string(형식 문자열) ~
printf
의 입력
- Format specifier 가 포함된 문자열
- 최종 문자열의 형태는 Format specifier의 부분이 확정되어야 결정 된다.
printf
의 첫 번째 인자
Format specifier(형식 지정자)
- "%d", "%o" 등 특수한 형태로 해당 서식의 형태를 결정 해준다.
#include <cstdio>
int main()
{
printf("Hello %d",10);
printf("%d + %d = %i\n", 2, 3, 2 + 3); // 2 + 3 = 5
printf("%u\n", -1); // 4294962795 ~ 4byte unsigned integer의 최대값 = 2^32 -1
}
#pragma warning(disable: 4996)
#include <cstdio>
int main()
{
{
// signed int 10진수 출력
printf("%d + %d = %i\n", 2, 3, 2 + 3);
}
{
// unsigned int 10진수 출력
printf("%u + %u = %u\n", 3, 2, 3 + 2);
}
{
// unsigned int 10진수 출력 형식으로 음수 int 출력
printf("%u\n", -1); // 4294962795 ~ 4byte unsigned integer의 최대값
}
{
// unsigned char 10진수 출력 형식으로 음수 int 출력
printf("%hhu\n", -1); 255 ~ 8bit 양수의 최대값
}
{
// char 출력
char ch = 'b';
printf("%c%c\n", 'a', ch);
}
{
// 부동소수점 출력(%f, %lf 같음)
printf("%f - %f = %lf\n", 2.0, 3.0f, -1.0f);
}
{
// unsigned int 8, 16진수 출력
printf("%o, %x, %X\n", 10, 10, 10);
}
{
// unsigned char 16진수 출력
printf("%hhx\n", 255);
}
{
// unsigned char 16진수 출력(overflow)
printf("%hhx\n", 256);
}
%f 인자의 경우 다 double로 형변환됨.
%hh = unsigned character 로 8비트 양수만 표현가능하기 때문에 0 ~ 최대 255까지 표현 가능함
#include <cstdio>
int main()
{
printf("%010d\n",1); // 0000000001 ~ 앞을 0으로 채우고 전체 개수를 10개로 맞춤
printf("%010d\n",-1); // -000000001
printf("%010f\n",1.1); // 001.100000
printf("%010f\n",-1.1);// -01.100000
printf("%010.1f\n",1.1); // 00000001.1
printf("%010.1f\n",-1.1);// -0000001.1
// 여백 추가하기 ~ 오른쪽에 붙이기
printf("%10d\n",1); // 1
printf("%10d\n",-1); // -1
printf("%10f\n",1.1); // 1.100000
printf("%10f\n",-1.1);// -1.100000
// 여백 추가하기 ~ 왼쪽에 붙이기
printf("%-10da\n",1); // 1 a
printf("%-10da\n",-1); // -1 a
printf("%-10fa\n",1.1); // 1.100000 a
printf("%-10fa\n",-1.1);// -1.100000 a
}
#include <cstdio>
using namespace std;
int main()
{
freopen("output.txt","w", stdout); // stdout을 콘솔이 아닌 텍스트 파일로 스트림을 바꾸고, 해당 파일에 write함.
printf("Hello World");
}