cout.width & setw & setfill / const

RushBsite·2022년 6월 18일
0

TIL

목록 보기
14/18
post-thumbnail

cpp 출력에서 자리수 채우기

cout.width

std::ios_base::width

The field width determines the minimum number of characters to be written in some output representations....
https://cplusplus.com/reference/ios/ios_base/width/

width 구문으로 다음 cout 출력값의 자리수를 강제할 수 있다.

예시

#include <iostream>

int main() {
	int x = 44;
	int y = 55;
	cout << x << endl; // 44
	cout.width(6); // 출력칸 = 6 지정
	cout << x << endl; // 앞에 4칸 띄운 44
	cout << y << endl; // 그냥 55
	cout.width(6); // 출력칸 = 6 지정
	cout.fill('0'); // 빈칸을 0으로 채움
	cout << x << endl; // 000044
	cout.width(4); // 출력칸 = 4 지정
	cout.fill('0'); // 빈칸을 0으로 채움
	cout << std::left << x << endl; // 왼쪽에 써서 4400

	return 0;
}

출력값

setw & setfill

cout << setw(int n ) << setfill(char_type c) << endl;

https://cplusplus.com/reference/iomanip/setw/?kw=setw
https://cplusplus.com/reference/iomanip/setfill/?kw=setfill

setwsetfill을 사용해서 위의 width와 fill의 기능을 대체할 수 있다.

예시

#include <iostream>

int main() {
	int x = 44;
	int y = 55;
	cout << setw(6) << x << endl; //앞에 4칸 띄운 44출력
	cout << setw(6) << setfill('0') << x << endl; // 000044
	return 0;
}

출력


const

함수에서의 const 설명이 잘 나와 있어 link
https://agh2o.tistory.com/8

profile
게임 기획/개발 지망생

0개의 댓글