rand 함수 이용
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main(void) {
srand(static_cast<unsigned int>(time(nullptr)));
//static_cast : 컴파일 타입에 형변환
//static_cast<바꾸려고 하는 타입>(대상);
int randNumber = rand();
//rand(): 랜드는 씨드값을 부여하지 않으면 고정 순서 출력
cout << "randNumber : " << randNumber << endl;
int die = (randNumber % 6) + 1;
cout << "You rolled a " << die << endl;
return 0;
}
숫자 맞추기 게임
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main(void) {
srand(static_cast<unsigned int>(time(nullptr)));
int secretNumber = (rand() % 100) + 1;
int tries = 0;
int guess;
cout << "\tStart Game" << endl<<endl;
do{
cout << "Guess the secretNumber: ";
cin >> guess;
++tries;
if (guess > secretNumber) {
cout << "Too high" << endl;
}
else if (guess < secretNumber) {
cout << "Too low" << endl;
}
else {
cout << "Correct answer" << endl << "tries: " << tries << endl;
}
} while (secretNumber!=guess);
return 0;
}
현대 프로그래밍 언어는 데이터와 함수를 결합한 소프트웨어 객체(개체, 인스턴스)를 통해 작업할 수 있습니다. 객체의 데이터 요소를 멤버 변수라고 하고, 객체의 함수를 멤버 함수 혹은 메서드라고부릅니다.
예를 들어 외계 우주선에 대해 생각해봅시다. 외계 우주선 객체는 게임프로그래머에 의해 정의된 Spacecraft라는 새로운 타입 일 수 있으며, 에너지 수준이라는 멤버 변수와 무기를 발사하는 멤버 함수를 가질 수 있습니다. 에너지 수준은 int 타입의 멤버 변수 energy에 저장될 수 있으며, 무기를 발사하는 능력은 fireWeapon()이라고 부르는 멤버 함수에 정의될 수 있습니다. 같은 종류의 모든 객체는 동일한 기본 구조를 가지고 있으므로 각 객체는 동일한 데이터 멤버 및 멤버 함수 집합을 가질 것 입니다. 그러나 개별적으로 각 오브젝트는 멤버 변수에 대한 고유한 값을 가질 것입니다.
객체는 생성한 후에 멤버 선택 연산자(.)를 사용하여 멤버 변수와 멤버 함수에 접근할 수 있습니다.

C++의 스트링은 실제로는 오브젝트이며, 단순히 길이를 얻는 것 부터 복잡한 문자 대체를 수행하는 모든 것을 스트링 오브젝트로 다양한 작업을 수행할 수 있는 고유한 멤버 함수 집합체이다.
#include<iostream>
#include<string>
using namespace std;
int main(void) {
string word1 = "Game";
string word2 = "Over";
string word3(3,'!'); //느낌표 3개를 스트링 클래스 타입 객체에 저장("!!!")
string phrase = word1 + " " + word2 + word3;
//string 클래스에서 연산자 오버로드를 통해 문자열을 연결할 수 있도록 + 연산자가 구현이 되어있음
cout << "phrase : " << phrase << endl;
cout << "word1[0] : " << word1[0] << endl;
cout << phrase.find("Over") << endl;
phrase.erase(4, 5); //index 4번째 부터 뒤로 5개의 문자 삭제
cout << "The phrase is : " << phrase << endl;
phrase.erase();
if (phrase.empty()) {
cout << "\nThe phrase is no more." << endl;
}
else
cout << "phrase is : " << phrase << endl;
return 0;
}
C++에서는 C 스타일의 문자열 처리 방식보다는 string 클래스를 사용하면 문자열을 효율적으로 처리할 수 있습니다. 특히, 배열을 이용하면 편리합니다.
#include<iostream>
#include<string>
using namespace std;
int main(void) {
const int MAX_ITMES = 10;
string inventory[MAX_ITMES];
int numItems = 0;
inventory[numItems++] = "Sword";
inventory[numItems++] = "Armor";
inventory[numItems++] = "Shield";
cout << "Your items: ";
for (int i = 0; i < numItems; ++i) {
cout << inventory[i] << " ";
}
inventory[0] = "battle axe";
cout << "\nThe Item name: " << inventory[0] << " has " << inventory[0].size() << " letters in it" << endl;
if (numItems < MAX_ITMES) {
inventory[numItems++] = "healing posion";
}
else {
cout << "You have too many items and can't carrt another." << endl;
}
return 0;
}
#include<iostream>
#include<string>
using namespace std;
int main(void) {
string word1 = "Game";
char word2[] = " Over";
string phrase = word1 + word2;
if (word1 != word2) {
cout << "word1 and word2 are not equal." << endl;
}
if (word2 != word1) {
cout << "word2 and word1 are not equal." << endl;
}
if (phrase.find(word2) != string::npos) {
//string::npos란 -1 값을 가지는 상수로 find() 함수 수행 시에 찾는 문자열이 없을 때 반환된다.
cout << "word2 is contained in phrase." << endl;
}
return 0;
}
다차원 배열
#include<iostream>
#include<string>
using namespace std;
int main(void) {
const int ROWS = 3;
const int COLS = 3;
char board[ROWS][COLS] = {
{'O','X','O'},
{' ','X','X'},
{'X','O','O'}
};
cout << "Here's the tic-tac-toe-borad" << endl;
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
cout << board[i][j];
}
cout << endl;
}
cout << endl << "'X' moves to the empty location." << endl << endl;
board[1][0] = 'X';
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
cout << board[i][j];
}
cout << endl;
}
cout << endl << "'X' wins!";
return 0;
}