在只使用 Python 太久之后,我正在努力重新熟悉 C++。我已经用 MS Visual C++ 2010 Express 版本编写了一个小程序,并且我到处寻找导致编译器似乎不喜欢我使用枚举类 Choice 的罪魁祸首。编译器抱怨不存在具有此名称的命名空间。现在,我应该说我之前编写的所有 C/C++ 代码都是在学术环境中,因此我使用的是完整的 IDE。无论如何,我在下面附加了代码,如果这是不正确的发布方法,请原谅我。如果是,请向我推荐正确的方法,我将在以后使用它。提前感谢您提供任何可以提供的帮助或见解。代码如下:
#include"stdafx.h"
#include<iostream>
#include<string>
#include<ctime>
using namespace std;
enum class Choice { rock, paper, scissors };
using namespace Choice;**
Choice player_choice; //holds user's move
Choice machine_choice; //holds machine's move
string words[3] = {"rock","paper","scissors"};
Choice get_machine_choice();
void decide_winner();
string get_msg(Choice winner);
int rand0toN1(int n);
int main(int argc, char *argv[])
{
srand(time(NULL)); //set randomization
string input_str;
int c;
while (true) {
cout << "Enter Rock, Paper, Scissors, or Exit: ";
getline(cin, input_str);
if (input_str.size() < 1) {
cout << "Sorry, I don't understand that.\n";
continue;
}
c = input_str[0];
if (c == 'R' || c == 'r')
player_choice = rock;
else if (c == 'P' || c == 'p')
player_choice = paper;
else if (c == 'S' || c == 's')
player_choice = scissors;
else if (c == 'E' || c == 'e')
break;
else {
cout << "Sorry, I don't understand that.\n";
continue;
}
machine_choice = get_machine_choice();
int p = (int) player_choice;
int c = (int) machine_choice;
cout << "You Choose " << words [p];
cout << "," << endl;
cout << "I choose " << words [c];
cout << "," << endl;
decide_winner();
}
return EXIT_SUCCESS;
}
Choice get_machine_choice() {
int n = rand0toN1(3);
if (n == 0) return rock;
if (n == 1) return paper;
return scissors;
}
void decide_winner() {
if (player_choice == machine_choice) {
cout << "Reult is a tie.\n\n";
return;
}
int p = static_cast<int>(player_choice);
int c = static_cast<int>(machine_choice);
if (p - c == 1 || p - c == -2) {
cout << get_msg(player_choice);
cout << "Unfortunantly, you win...\n";
} else {
cout << get_msg(machine_choice);
cout << "I WIN, BEEEATCH!!!!\n";
}
cout << endl;
}
string get_msg(Choice winner) {
if (winner == rock)
return string("Rock smashes scissors, beeatch...");
else if (winner == paper)
return string("You know what paper does to rock, COVERAGE!!...");
else
return string("CHOP! Scissors cut paper!!....");
}
int rand0toN1(int n) {
return rand() % n;
}
再次感谢您花时间帮助我。我似乎记得经常使用 C++ 声明类,但不知道为什么它不能识别它。