개발하는 리프터 꽃게맨입니다.

[C++] 조정자 (Manipulator) 본문

언어/C, C++

[C++] 조정자 (Manipulator)

파워꽃게맨 2023. 12. 24. 22:55

C언어의 서식 지정자의 C++ 버전입니다.

제가 나중에 참고하기 위해서 정리했습니다.

 

📘 문법

1. C++ 스타일 기본 조정자

#include <iostream>
#include <iomanip> //setw 를 사용할 수 있는 라이브러리
using namespace std;

int main()
{

	cout << showpos << 123 << endl;		 // + - 부호 문자 출력
	cout << noshowpos << 123 << endl;	 // - 부호 문자만 출력

	cout << dec << 123 << endl;		//10진수 출력
	cout << hex << 123 << endl;		//16진수 출력
	cout << oct << 123 << endl;		//8진수 출력

	cout << uppercase << hex << 1234 << endl;	//16진수 알파벳 대문자
	cout << nouppercase << hex << 1234 << endl;	//16진수 알파벳 소문자 (기본 설정)

	cout << dec;
	cout << setw(10) << left << -123 << endl;		//왼쪽 정렬
	cout << setw(10) << internal << -123 << endl;	//부호 왼쪽, 숫자 오른쪽 정렬
	cout << setw(10) << right << -123 << endl;		//오른쪽 정렬

	cout << noshowpoint << 100 << " " << 100.123456<<endl;  //필요없는 소수점 아래 문자 제거
	cout << showpoint << 100 << " " << 100.123456<<endl;  //소수점 아래 문자 출력

	cout << fixed << 123.456789 << endl;		//일반적인 방식으로 숫자 출력
	cout << scientific << 123.456789 << endl;	//정규화

	cout << boolalpha << true << endl;		//bool를 문자로 출력
	cout << noboolalpha << true << endl;	//bool를 숫자(0, 1)로 출력

	return 0;
}

 

<출력>

 

 

2. <iomanip> 라이브러리

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{

	cout << setw(5) << 123 << endl;					//C의 정수 서식 지정자와 기능 동일
	cout << setfill('*') << setw(5) << 123 << endl;	//빈 공간을 지정 문자로 채움
	cout << setprecision(3) << 123.456789 << endl;	//소수점 n번 째 까지 출력

	return 0;
}

 

<출력>

 

📘 주의할 점

모든 설정은 한 번 지정하면, 한 번만 양식이 사용되는 것이 아닌

계속 설정이 유지됩니다.