feat. FOCU teachable
C++
1988 ~ 2018 까지 C/C++ 프로젝트들이 JAVA 로 대체되었음
속도가 중요하지 않는 프로그램들, 실시간 시뮬레이션을 하지 않는 프로그램처럼 프로그래머가 직접 메모리단을 직접 다루지 않는 안전한 언어가 필요하여 JAVA 가 대두됨
이로 인해 C/C++ 도 COBOL 처럼 사라질 것으로 추측
그러나 점유율로 봤을 땐 C/C++ 이 조금 더 우세한 편으로
JAVA 등의 매니지드 언어(managed language)는 완전히 C/C++ 을 대체할 수 없음
- JAVA 를 포함한 많은 언어들이 매니지드 언어
- C/C++ 을 언매니지드 이고, 이를 대체할 만한 경쟁 언어가 없음
LINUX, iOS, X, Windows10, android 등등에 사용됨
임베디드 시스템에서도 사용
비디오 게임에서도 사용
- C/C++ 을 많이 사용하는 업계
- 상용 게임 엔진 (언리얼 엔진, 크라이 엔진 등)
- 3D 비디오 게임
그래픽 어플리케이션에서도 사용
- 어도비 포토샵, 어도비 일러스트레이터, 오토데스크 마야 등
웹브라우저 대부분
- 모질라 파이어폭스, 구글 크롬, 인터넷 익스플로러 등
의료 장비
- CT, MRI, 혈압 측정기, 심장 받동 모니터기 등
출력(Output)
ex) "Hello world 123" 출력
std::cout << "Hello " << "world " << 123 << std::endl
std::
- 네임스페이스(namespase)
- JAVA 의 패키지나 C# 의 네임스페이스와 비슷
- 다음과 같은 것들의 이름 충돌을 피하기 위해 사용
함수
클래스
기타 등등
namespace hello - 소문자를 사용하는게 일반적
{
void PrintHelloWorld();
}
ㄴ hello 라는 네임스페이스 안에 PrintHellowWorld() 함수를 담았다
namespace hello
{
void SayHello();
}
namespade hi
{
void SayHello();
}
// ...
hello::SayHello();
hi::SayHello();
C 같은 경우 SayHello 라는 함수의 중복으로 컴파일 오류를 발생시키지만, C++ 같은 경우 별개의 함수로 인지가능
여기서 endl 과 직접 '\n' 의 입력의 차이를 잠깐 설명하자면
- endl 로 입력시에 스트림을 flush 함
- '\n' 직접 입력시 스트림을 flush 하지 않음
flush 란?
버퍼(buffer)에 저장된 데이터를 강제로 출력 장치(예: 화면, 파일 등)로 내보내는 것
C++에서 cout 같은 출력 스트림은 효율성을 위해 출력 내용을 메모리 내의 버퍼에 임시 저장함
바로바로 화면에 출력되는 것이 아니라, 어느 정도 쌓인 뒤에 한꺼번에 출력되는 구조로,
이 버퍼를 강제로 비워서 즉시 출력하게 만드는 것이 flush 이다.
using 지시문
JAVA 의 import 나 C# 의 using 과 비슷
타이핑의 양을 줄이는 방법일 뿐..
네임스페이스 입력 같은 걸 생략 가능하게 해줌
#include <iostream>
int main()
{
std::cout << "Hello, world!" << std::endl
return 0;
}
------------------------------------------------
// using 사용으로 인한 코드 변화
#inlcude <iostream>
using namespace std;
int main()
{
cout << "Hello, world!" << endl;
return 0;
}
<< 연산자 insertion operator
보통 정식 이름인 'insertion 연산자' 보단 '출력 연산자' 또는 'push 연산자' 로 불리기도 함
C++ 에서는 프로그래머가 연산자의 동작을 바꿀 수 있음
// 사용 예문
#include <iostream>
#include "PrintEverything.h"
using namespace std;
namespace samlples
{
void PrintEverythingExample()
{
int integer = 10;
float decimal = 1.5f;
char letter = 'A'
char string[] = "Hello, world!";
cout << integer << endl;
cout << decimal << endl;
cout << letter << endl // 세미콜론이 없으면 이어서 계속 출력가능
<< string << endl; // 22 번과 이어지는 한 줄 짜리 코드이나 가독성을 위해 줄바꿈 적용
}
}
출력형식 지정 Output formatting
C 에서의 출력형식은 가독성이 부족하고, 사용성의 불편함이 있음
// C 로 16 진수 출력 예시
int number = 10;
printf("%x\n", number); // a
printf("%#x\n", number); // 0xa
C++ 에서 조정자(Manipulator)를 통해 좀 더 유연하게 사용하고자 하여 다음과 같이 사용함
// C++ 출력 예시
int number = 10;
cout << showbase << hex << number << endl;
순차적으로 읽어보면 C 의 형식자를 해석하는 것보다 쉬움
다음과 같이 여러 조정자가 있음을 알 수 있음
#include <iostream>
using namespace std;
int number = 123;
// showpos/noshowpos
cout << showpos << number; // +123
cout << noshowpos << number; // 123
// dec/hex/oct
cout << dec << 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
----------------------------------------------------------------------------------------------------------------------
int number = -123
float decimal1 = 100.0;
float decimal2 = 100.12;
// left/internal/right
cout << setw(6) << left << number; // |-123 |
cout << setw(6) << internal << number; // |- 123|
cout << setw(6) << right << number; // | -123|
// showpoint/noshowpoint
cout << noshowpoint << decimal << " " << decimal2 //100 100.12 소수점 끝이 0 일 경우 생략
cout << showpoint << decimal << " " << decimal2 // 100.100 100.120 소수점 끝을 기본 3자리까지 출력
----------------------------------------------------------------------------------------------------------------------
float decimal = 123.456789;
bool bReady = true;
// fixed/scientific
cout << fixed << number; //123.456789
cout << scientific << number; //123.456798E+02
// boolalpha/noboolalpha
cout << boolalpha << bReady; // true
cout << noboolalpha << bReady; // 1
예문을 보면 조정자가 no~ 로 시작하는 것들이 존재하는데
나는 이 부분이 의문이었던 게, 조정자를 사용하지 않으면 값 그대로 출력이 될텐데 왜 굳이 no~ 라는 조정자를 하나 더 만들었을까에 대한 의문을 가졌고, 이에 대해 도출된 답은
'조정자는 on/off 버튼' - 이라는 답이었다.
한 번 조정자를 적용시키면, 이후 출력은 해당 조정자가 유효한 채로 출력이 된다는 부분을 알게 되었다
아래의 예시를 보면 알 수 있다.
#include <iostream>
using namespace std;
cout << showpos << number << " " << number << endl; // +123 +123
cout << showpos << number << " " << noshownuber << number << endl; // +123 123
// 또는
cout << showpos << number << endl; // +123
cout << number << endl; // +123
다음은 조정자는 <iomanip> 를 include 하면 사용할 수 있는 조정자들이다.
#include <iomanip> //.h 는 입력안함
using namespace std;
int number = 123;
float decimal = 123.456789;
// setw() - 칼럼수를 설정
cout << setw(5) << number; // | 123|
// setfill() - 빈 곳을 설정한 문자로 채워줌
cout << setfill('*') << set(5) << number; // |**123|
// setprecision() - 설정한 소수점 자리수만 출력하고 반올림처리
cout << setprecision(7) << number; // 123.4568
cout << setprecision(6) << number; // 123.457 - C++ 의 default 소수점 6자리로 원복
다음과 같은 종합 예문으로 다시 확인해보자
#include <iomanip>
#include <iostream>
#include "PrintMenu.h"
using namespace std;
namespace samples
{
void PrintMenuExample()
{
const float coffePrice = 1.25f;
const float latterPrice = 4.75f;
const float breakfastComboPrice = 12.104f;
const size_t nameColumnLength = 20;
const size_t priceColumnLength = 10;
cout << left << fixed << showpoint << seprecision(2);
cout << setfill('-') << setw(nameColumnLength + priceColumnLength) << "" << endl << setfill(' ');
cout << setw(nameColumnLength) << "Name"
<< setw(priceColumnLength) << "Price" << endl;
cout << setw(nameColumnLength) << "Coffee"
<< "$" << coffeePrice << endl;
cout << setw(nameColumnLength) << "Latte"
<< "$" << latterPrice << endl;
cout << setw(nameColumnLength) << "Breakfast Combo"
<< "$" << breakfastComboPrice << endl;
}
}
cout 메서드
- 조정자를 함수로 구현
- 잘 사용하진 않음
cout << showpos << number;
---------------------------------------------------------
cout.setf(ios_base::showpos);
cout << number
_________________________________________________________
cout << setw(5) << number;
---------------------------------------------------------
cout.width(5);
cout << number;
네임스페이스
setf(), unsetf()
width(), fill(), precision()
등등 사용가능
setf/unsetf
인자
boolalpha
showbase
uppercase
showpos
set(flag, flag)
인자
dec, basefield
oct, basefield
hex, basefield
fixed, floatfield
scientific, floatfield
left, adjustfield
ritght, adjustfield
internal, adjustfield
'C++ > FOCU_C++' 카테고리의 다른 글
C++ chpt6. (1) | 2025.05.16 |
---|---|
C++ chpt5. (0) | 2025.05.04 |
C++ chpt4. (0) | 2025.05.03 |
C++ chtp3. (0) | 2025.05.03 |
C++ chpt2. (0) | 2025.04.29 |