코테용 C++ 핵심 정리 무료 강의 3시간 – 홍정모
- Hello World 헬로우 월드
- 윈도우 한글 입출력 설정
- 자료형
- 배열
- 콘솔 입출력
- 분기
- 반복
- 숫자 맞추기 게임
https://www.youtube.com/watch?v=UqCZda8DLGc
https://github.com/HongLabInc/HongLabCppSummary
1. Hello World 헬로우 월드
/*
홍정모 연구소 https://honglab.co.kr/
*/
#include <iostream> // iostream이라는 헤더를 포함(include)
// 자주 사용하는 입출력 기능이 iostream 파일 안에 들어 있고 그 내용을 전부 인클루드해서 밑에서 사용 가능
// # 기호는 특수하기 때문에 끝에 세미콜론을 안 씀
using namespace std; // 네임스페이스 설명 std::cout
// std:: 가 없더라도 컴파일러가 알아서 찾아줌.
int main() // entry point
{
// 주석(comment) 다는 방법
cout << "Hello, World!" << endl;
// printf("Hello World!!! by printf");
// 입출력에 대해서는 뒤에 다시 나와요.
char user_input[100];
cin >> user_input;
cout << user_input;
return 0; // 0을 반환하면 운영체제에게 잘 끝났다고 알려줌.
}
2. 윈도우 한글 입출력 설정
3. 자료형
int main()
{
// 변수를 정의할 때 자료형을 미리 지정해야 합니다.
// 자료형은 바꿀 수 없습니다.
// 내부적으로 메모리를 이미 갖고 있습니다.
int i; // 변수 정의
i = 123; // 변수에 값 지정 (객체 레퍼런스 아님)
// sizeof 소개
cout << i << " " << sizeof(i) << endl; // 추측해보세요.
float f = 123.456f; // 마지막 f 주의
double d = 123.456; // f 불필요
cout << f << " " << sizeof(f) << endl; // 123.456 4
cout << d << " " << sizeof(d) << endl; // 123.456 8
// C++는 글자 하나와 문자열을 구분합니다.
char c = 'a';
char str[] = "Hello, World!";
cout << c << " " << sizeof(c) << endl; // a 1
// 그 외에도 다양한 자료형이 존재합니다.
----------------------------
// 형변환
i = 987.654; // double을 int에 강제로 저장
cout << "int from double " << i << endl; // 반올림이 아닌 버림한다. 987
f = 567.89; // 이것도 형변환 (8바이트 double을 4바이트 float 로 강제 변환)
f = 567.89f; // 형변환 아님
----------------------------
// 기본 연산자
// i = 987;
i += 100; // i = i + 100;
i++; // i = i + 1;
cout << i << endl; // 추측해보세요. 1088
----------------------------
// 불리언
bool is_good = true;
is_good = false;
cout << is_good << endl; // 0
// boolalpha : true, false 로 출력
// noboolalpha : 1, 0 으로 출력
cout << boolalpha << true << endl; // true
cout << is_good << endl; // false
cout << noboolalpha << true << endl; // true
// 논리 연산 몇 가지 소개 (참고 문서 사용)
// https://en.cppreference.com/w/cpp/language/operator
cout << boolalpha;
cout << (true && true) << endl; // 연산자 우선순위때문에 괄호 필요 true
cout << (true || false) << endl; // 추측해보세요. true
----------------------------
// 비교
cout << (1 > 3) << endl;
cout << (3 == 3) << endl;
cout << (i >= 3) << endl;
cout << ('a' != 'c') << endl;
cout << ('a' != 'a') << endl;
----------------------------
// 영역 (scope)
i = 123; // 더 넓은 영역
{
int i = 345; // <- 더 좁은 영역의 다른 변수
cout << i << endl; // 345
}
cout << i << endl; // 123
return 0;
}
4. 배열
using namespace std;
int main() {
int a = 1;
int b = 2;
int c = 3;
// ...
// 같은 자료형의 데이터를 저장하기 위해 메모리를 미리 잡아놓은
int my_array[3] = {1, 2, 3}; // 초기화할 때는 {} 안에 값 나열
// 인덱싱 (zero-based)
cout << my_array[0] << " " <<
my_array[1] << " " <<
my_array[2] << endl; // 추측해보세요 1 2 3
// 인덱싱으로 하나 짜리 변수 처럼 사용 가능
my_array[1] = 5;
cout << my_array[0] << " " <<
my_array[1] << " " <<
my_array[2] << endl; // 추측해보세요 1 5 3
// cout << my_array[10000] << endl; // 오류 발생
// 문자열은 기본적으로 문자의 배열
char name[75] = "Hello, World!"; // 문자''와 문자열"" 구분
cout << name << " " << sizeof(name) << endl; // Hello, World! 75
char name[14] = "Hello, World!"; // 배열 크기를 문자열에 맞게 지정하려면
// 마지막에 Null character '\0' 가 있으므로 13이 아닌 14
// 배열 크기를 지정하지 않으면 컴파일러가 자동으로 계산
char name[] = "Hello, World!";
cout << name << " " << sizeof(name) << endl; // Hello, World! 14
name[10] = 'A';
name[11] = 'B';
name[12] = 'C';
cout << name << endl; // Hello, WorABC
name[2] = '\0'; // 추측해보세요
cout << name << endl; // He
return 0;
}
5. 콘솔 입출력
int main() {
// cin은 데이터를 흘려넣어 보내는 스트림이고
// 그 데이터를 해석하는 것은 자료형
// 자료형에 따라서 알아서 처리해주기 때문에 scanf()보다 편리
char user_input[100];
// cin과 getline의 차이
// cin은 빈 칸 또는 줄바꿈까지만 입력 받음.
cout << "원하는 문장을 입력해주세요." << endl;
cout << "입력: ";
// cin >> user_input;
// cin.getline은 배열과 크기를 지정해서 입력 받음
cin.getline(user_input, sizeof(user_input));
cout << "메아리: " << user_input << endl;
int number = -1;
cin >> user_input;
// cin.getline(user_input, sizeof(user_input));
// 최대 100글자까지 입력받고 무시하겠다. 또는 '\n'이 있으면 그때부터 무시하겠다. 둘 중에 하나만 만족해도 그 이후는 무시
cin.ignore(100, '\n');
cin >> number; // 위에서 "단어1 단어2"를 입력했다면 ignore 했기 때문에 여기서 입력 대기함.
cout << user_input << " " << number << endl;
// 참고 : cin.ignore(numeric_limits<streamsize>:: max(),'\n')
return 0;
}
6. 분기
#include <iostream>
using namespace std;
int main()
{
// 나머지 연산자 안내
// 줄 바꿈 '\n' newline
// 블럭 내용이 한 줄일 경우에는 {} 생략 가능
int number;
cin >> number;
if (number % 2 == 0)
{
cout << "짝수입니다.\n"; // cout << "짝수입니다." << endl;
// 추가적으로 할 일들
cout << "짝수라니까요!" << endl;
}
else
cout << "홀수입니다.\n";
// 조건 연산자 (삼항 연산자)
cout << (number % 2 == 0 ? "짝수입니다." : "홀수입니다.") << endl;
switch (number)
{
case 0:
cout << "정수 0입니다." << endl;
break; // 주의
case 1:
cout << "정수 1입니다." << endl;
break;
default:
cout << "그 외의 숫자입니다." << endl;
break; // 마지막은 생략 가능
}
return 0;
}
7. 반복
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 10; i++)
{
cout << i << " ";
}
// 배열 데이터 출력 연습 문제로 제공
// 힌트: sizeof(my_array) / sizeof(int)
int my_array[] = {1, 2, 3, 4, 5, 4, 3, 2, 1};
for (int i =0; i < sizeof(my_array) / sizeof(int); i++)
{
cout << my_array[i] << " ";
}
cout << endl;
// 문자열 출력
char my_string[] = "Hello\0, World!";
// 문자열을 한 글자씩 출력하기
// cout << my_string << endl; 사용 X
// 힌트: sizeof(), '\0', break,
for (int i =0; i < sizeof(my_string); i++)
{
if (my_string[i] == '\0')
break;
cout << my_string[i];
}
cout << endl;
for (int i = 0; my_string[i] != '\0'; i++)
{
cout << i << "" << my_string[i] << endl;
cout << endl;
}
int i = 0;
while (true) // for(;true;)
{
cout << i << " ";
i++;
if (i >=10)
break;
}
cout << endl;
// 런타임오류 주의
// while문으로 문자열 한글자씩 출력하기
// 힌트 && logical and
// char my_string[] = "Hello\0, World!";
// int i = 0;
i= 0;
while (i < sizeof(my_string) && my_string[i] != '\0')
{
cout << my_string[i];
i++;
}
cout << endl;
return 0;
}
8. 숫자 맞추기 게임
int main()
{
// 난수 생성
// https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distrib(1, 99); // [1, 99]
int number = distrib(gen);
while (1) // true 대신 숫자 1로 무한 반복도 많이 사용
{
int guess;
cout << “입력: ";
cin >> guess;
if (guess == number)
{
cout << "정답!" << endl;
break; // 힌트
}
else if (guess > number)
{
cout << "너무 커요!" << endl;
}
else
{
cout << "너무 작아요!" << endl;
}
}
return 0;
}