C,C++/CONCEPT

C++ std:setw()

너래쟁이 2018. 3. 5. 15:30

[ std::setw() ]


 " std::setw() " 함수는

 iomanip 헤더에 구현되어 있다.


 " std::setw() " 함수는 어떨때 쓰냐


 출력을 할 때

 " std::setw() " 호출할 때 넣은 첫 번째 매개변수 값 만큼

  폭이 설정되고 출력이 된다.


 " printf(" %3d ", 2); "

 를 할 경우 2의 값이 폭이 3만큼 설정된 상태에서 2 를 출력하는 경우와 마찬가지이다.


 간단하게 살펴보자


 [ source ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <iomanip>
#include <string>
 
int main()
{
    std::string a{"hi"};
 
    int n = 12;
 
    std::cout << std::setw(5<< a << std::endl;
 
    std::cout << std::setw(5<< n << std::endl;
 
    return 0;
}
cs


 [ 실행 결과 ]

  



--------------------------------------------------



 이번에는 입력부분을 보자.


 " std::setw() " 호출할 때 넣은 매개변수 값 만큼의 폭만

 값을 저장 하게 된다.


 입력부분을 찾아봤을 때 아래 사진과 같이

 " operator>> " 호출할 때의 매개변수를 보니

 string 혹은 *char 만 있는 관계로

 문자에 관련된 부분만 적용되는 것 같다.


 



 실험해봤는데 정말 숫자에 관련된 부분은 안먹혔다.


 한번 string 으로 간단하게 실험해보았다.


 [ source ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <iomanip>
#include <string>
 
int main()
{
    std::string str;
 
    std::cin >> std::setw(5>> str;
 
    std::cout << str << std::endl;
 
    return 0;
}
cs


 [ 실행 결과 ]

 

[출처] [C++] std::setw(int);|작성자 하하하