C++/Library
2021. 3. 29. 23:56
cout
<iostream>
라이브러리
출력 형식 설정
여러가지 방법으로 출력 형식을 설정할 수 있다.
+
부호 붙이기, 16진수 출력, 대문자 출력#include <iostream> int main() { using namespace std; cout.setf(std::ios::showpos); cout << 108 << endl; cout.unsetf(std::ios::showpos); cout << 108 << endl; cout.unsetf(std::ios::dec); cout.setf(std::ios::hex); cout << 108 << endl; cout.setf(std::ios::hex, std::ios::basefield); cout << 108 << endl; cout << std::dec; cout << 108 << endl; cout.setf(std::ios::uppercase); cout << std::hex; cout << 108 << endl; cout << std::nouppercase; cout << 108 << endl; cout << boolalpha << true << ' ' << false << endl; cout << noboolalpha << true << ' ' << false << endl; }
/* stdout stderr
+108
108
6c
6c
108
6C
6c
true false
1 0
*/
## `<iomanip>`
- `<iomanip>` 라이브러리를 포함하면 더 유연하게 출력 형식을 조절할 수 있다.
- 소수점 자릿수 조절, 과학적 표기법, 소수점 표시
```c++
#include <iostream>
#include <iomanip>
void printFloat()
{
using namespace std;
cout << std::setprecision(3) << 123.456 << endl;
cout << std::setprecision(4) << 123.456 << endl;
cout << std::setprecision(5) << 123.456 << endl;
cout << std::setprecision(6) << 123.456 << endl;
cout << std::setprecision(7) << 123.456 << endl;
cout << endl;
}
int main()
{
using namespace std;
printFloat();
cout << std::fixed;
printFloat();
cout << std::scientific << std::uppercase;
cout << "this is lowercase\n";
printFloat();
cout << std::defaultfloat;
cout << std::showpoint;
printFloat();
}
/* stdout stderr
123
123.5
123.46
123.456
123.456
123.456
123.4560
123.45600
123.456000
123.4560000
this is lowercase
1.235E+02
1.2346E+02
1.23456E+02
1.234560E+02
1.2345600E+02
123.
123.5
123.46
123.456
123.4560
*/
좌우 정렬, 공백 대신 문자 채우기
#include <iostream> #include <iomanip> int main() { using namespace std; cout << -12345 << endl; cout << std::setw(10) << -12345 << endl; cout << std::setw(10) << std::left << -12345 << endl; cout << std::setw(10) << std::right << -12345 << endl; cout << std::setw(10) << std::internal << -12345 << endl; cout << endl; cout.fill('*'); cout << std::setw(10) << -12345 << endl; cout << std::setw(10) << std::left << -12345 << endl; cout << std::setw(10) << std::right << -12345 << endl; cout << std::setw(10) << std::internal << -12345 << endl; }
/* stdout stderr
-12345
-12345
-12345
-12345
12345
****12345
12345****
***-12345
****12345
/
```
'C++ > Library' 카테고리의 다른 글
C++ 정규 표현식 (Regular Expressions) (0) | 2021.03.29 |
---|---|
C++ 흐름 상태 (Stream States) (0) | 2021.03.29 |
C++ ostream (0) | 2021.03.29 |
C++ istream (0) | 2021.03.29 |
C++ wstring (0) | 2021.03.26 |