[C++] cout
이 글은 패스트캠퍼스 C++ 실력 완성 올인원 패키지 Online.를 보고 따라 만들면서 헷갈리는 부분을 정리한 글입니다.
coutPermalink
c++에서는 cout을 통해서 출력을 할 수 있다.
#include <iostream>
using namespace std;
int main()
{
cout << "출력";
}
// 출력 결과
// 출력
cout.widthPermalink
width를 통해 정해준 최소 길이로 출력할 수 있다.
int main()
{
cout.width(5);
cout << 1;
}
// 출력 결과 (4칸 띄고 1)
// 1
cout.fillPermalink
fill을 통해 빈 공간을 정해준 문자로 채울 수 있다.
int main()
{
cout.width(5);
cout.fill('#');
cout << 1 << endl;
}
// 출력 결과
// ####1
cout.precisionPermalink
부동 소수점 같은 값을 출력할 때 정밀도를 설정할 수 있다.
int main()
{
float num = 0.1234567f;
cout << num << endl;
cout.precision(64);
cout << num << endl;
}
// 출력 결과
// 0.123457
// 0.12345670163631439208984375
cout.setf로 플래그 설정Permalink
setf를 통해서 플래그를 설정하여 어떤 식으로 출력할지를 결정할 수 있다.
밑의 예시 외에도 많은 플래그 설정이 가능
int main()
{
// + 부호를 부여줌
cout.setf(ios_base::showpos);
cout << 1 << endl;
// 플래그 해제
cout.unsetf(ios_base::showpos);
// boolean 형을 true false로 출력함
cout.setf(ios_base::boolalpha);
cout << true << endl;
cout << false << endl;
// 플래그 해제
cout.unsetf(ios_base::showpos);
// 왼쪽 정렬을 함
cout.setf(ios_base::left, ios_base::adjustfield);
cout.width(10);
cout << 1 << 2;
}
// 출력 결과
// +1
// true
// false
// 1 2
cout 안에서 설정Permalink
iomanip를 include하여 cout안에서 위에서 한 작업을 할 수 있다.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setw(10) << setfill('#') << setprecision(1) << showpos << 1.1f;
}
// 출력 결과
// ########+1
댓글남기기