Search

C++ | 정수 출력 시 자릿수 맞추기 (setw, setfill)

Date
2024/07/28
category
C++
Tags
c++

1. setw와 setfill

출력 스트림 동작을 조작할 수 있는 있는 manipulator 객체
<iomanip> 헤더에 선언이 존재
setw
숫자 데이터 출력 시 필드의 너비 지정
바로 다음 출력에만 적용
setfill
숫자의 자릿수가 필드 너비보다 작을 때 필드를 채울 문자 지정
한번 설정 후 계속 적용

2. 예제

#include <iostream> #include <iomanip> int main() { int sec = 0; int min = 0; int hour = 0; std::cin >> sec; hour = sec / 3600; min = (sec % 3600) / 60; sec = (sec % 3600) % 60; std::cout << std::setfill('0'); std::cout << std::setw(2) << hour << ":" << std::setw(2) << min << ":" << std::setw(2) << sec << std::endl; return 0; }
C++
복사
초를 입력받고 시:분:초 형식으로 출력하는 코드
setfill: 필드를 채울 문자로 ‘0’ 설정
setw: 필드 너비를 2로 지정, 다음 출력에만 적용되므로 출력할 때 마다 설정