C++로 만든 숫자 야구 게임이다.
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(int argc, char *argv[]) {
vector < int > num(3);
vector < int > set(3);
int cnt = 0;
int s = 0;
int b = 0;
for (int i = 0; i < 3; i++) {
srand((unsigned int) time(NULL));
set[i] = (rand() % 9) + 1;
for (int j = 0; j < i; j++) {
if (set[i] == set[j]) {
i--;
break;
}
}
}
while (s != 3) {
string st;
cout << "3자리 숫자를 입력하세요 (1 ~ 9)." << endl;
getline(cin, st);
if (st.length() != 3) {
cout << "숫자를 입력해야 합니다." << endl;
continue;
}
int flag = 0;
for (int i = 0; i < st.length(); i++) {
if (st[i] < '1' || st[i] > '9') {
cout << "1 ~ 9 사이의 숫자를 입력해야 합니다." << endl;
flag = 1;
break;
}
}
if (flag == 1) {
continue;
}
num[0] = st[0] - '0';
num[1] = st[1] - '0';
num[2] = st[2] - '0';
if (num[0] == 9 && num[1] == 9 && num[2] == 9) {
for (int i = 0; i < 3; i++) {
cout << set[i];
}
cout << " <-- Hint \n";
continue;
}
if (num[0] == num[1] || num[1] == num[2] || num[2] == num[0]) {
cout << "서로 다른 3자리 숫자를 입력해야 합니다 (1 ~ 9)." << endl;
continue;
}
s = 0;
b = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (set[i] == num[j]) {
if (i == j) {
s++;
} else {
b++;
} //if
} //if
} // for
} //for
cout << s << "S " << b << "B " << endl;
cnt++;
} // while
cout << cnt << " 번 만에 맞추었습니다" << endl;
}
int main(int argc, char *argv[]) 는 int main(int argc, char **argv) 로 변경하여 사용해도 된다.
'C++ 언어' 카테고리의 다른 글
| C++에서 Vector를 사용하여 문자열 정력하기(중복테이타 제외) (0) | 2021.09.10 |
|---|---|
| C++에서 Left Right Mid Trim함수 사용하기 (0) | 2021.09.10 |
| C++에서 Vector를 사용하여 자료를 추가히고 출력하기 (0) | 2021.09.10 |
| C++에서 문자열을 정수로 변환하기 (0) | 2021.09.09 |
| C++에서 3자리 숫자 입력 받기 (0) | 2021.08.13 |
댓글