공부를 시작하면서 제일 첫 단계는 "Hello World"를 화면에 출력하는것이다.
기본적인 출력문을 하나하나 뜯어보는 단계를 가져보겠다.
std::cout << "Hello World" << endl;
한 줄 해석: namespace std에 있는 cout 명령을 사용해서 "Hello World"를 출력하고 개행해라.
std::
용도: [namespace]::
namespace
Java의 패키지, C#의 네임스페이스와 비슷하게 사용됨. 이름 충돌을 피하기 위해 사용하는 grouping 방법
namespace hello
{
void PrintHello();
}
hello::PrintHello();
cout
용도: console out (print 기능)
<<
용도: Insertion operator (삽입 연산자, 밀어넣는 연산자, push 연산자)
뒷 명령어를 앞 명령어에 밀어넣는다.
윗 예제의 경우, "Hello World" 스트링을 cout 에 밀어넣으므로 출력이 된다.
endl
용도: 개행 (\n)
using
용도: 타이핑을 줄여주는 namespace 선언자. Java의 import, C#의 using과 비슷
using namespace std;
cout << "Hello World" << endl;
#pragma once
용도: 헤더파일 중복 인클루드를 막기 위해 C++ 컴파일러에게 지시하는 명령어 (한번만 인클루드 되도록) #if, #ifdef, #ifndef 와 같은 기능을 한다.
출력 형식 지정 (output formatting) - Manipulator (조정자)
- showpos/noshowpos // pos == positive 양수 ('+'사인 붙이기)
// number가 123이라면,
cout << showpos << number; // +123
cout << noshowpos << number; // 123
- dec/hex/oct (10/16/8진수)
cout << dev << number; // 123
cout << hex << number; // 7b
cout << oct << number; // 173
- uppercase/nouppercase : 대문자 변환
cout << uppercase << hex << number; // 7B
cout << nouppercase << hex << number; // 7b
- showbase/noshowbase : 진법 표기
cout << showbase << hex << number << endL; //0x7b
cout << noshowbase << hex << number << endL; // 7b
- left/internal/right : 지정 크기 내 문자 정렬
// number의 값이 -123이라면,
cout << setw(6) << left << number; // |-123 |
cout << setw(6) << internal << number; // |- 123| (부호는 왼쪽에, 숫자는 오른쪽에, 회계용)
cout << setw(6) << right << number; // | -123|
-showpoint/noshowpoint : 소숫점 이하 자리수를 강제로 보여줄까 말까
// decimal의 값이 100.0, decimal2의 값이 100.12라면
cout << noshowpoint << decimal1 << " " << decimal2; // 100 100.12
cout << showpoint << decimal1 << " " << decimal2; // 100.000 100.120
-fixed/scientific(정수부+소수부)
// number의 값이 123.456789라면,
cout << fixed << number; // 123.456789
cout << scientific << number; // 1.234568E+02
-boolalpha/noboolalpha
// bReady의 값이 true라면,
cout << boolalpha << bReady; // true
cout << noboolalpha << bReady; // 1
-setw() : 공간 크기 지정
// number의 값이 123이라면,
cout << setw(5) << numer; // | 123|
-setfill() : 빈 공간을 지정문자로 채우기
cout << setfill('*') << setw(5) << number // **123
-setprecision() : 소수점 포함 몇자리까지 보여줄까?
// number의 값이 123.456789라면,
cout << setprecision(7) << number; // 123.4567
출력 형식 지정 (output formatting) - 멤버 메서드 (실제로는 manipulator를 더 많이 사용함)
멤버 메서드는 ios_base 네임스페이스 안에 있다.
manipulator(조정자) | 멤버 메서드 |
cout << showpos << number; |
cout.setf(ios_base::showpos); cout << number |
cout << setw(5) << number |
cout.width(5); cout << number; |
setf : set flag ( <-> unsetf )
width(), fill(), precision()
- setf와 unsetf는 인자를 한 개 받을 수도 있고, 두 개 받을 수도 있다.
- 1개일 때 받을 수 있는 인자: boolalpha, showbase, uppercase, showpos
- 2개일 때 받을 수 있는 인자:
첫 번째 인자 | 두 번째 인자 |
dex/oct/hex | basefield |
fixed/scientific | floatfield |
left/right/internal | adjustfield |
'C++' 카테고리의 다른 글
[C++ study] C++의 시작과 현재, 나와의 첫 대면 (0) | 2020.03.10 |
---|