我想在我编码的内容中有一个性别系统,所以在对话中有代词,但由于字符串是在if
语句中定义的,因此它们是空白的。有一个更好的方法吗?
int gender;
string pronoun;
string pronoun1;
string pronoun2;
string pronouns3;
string namingGender;
cout << "Please enter your gender \n1. Male \n2. Female \n3. Other" << endl;
cin >> gender;
if (gender == 1) {
string namingGender = " saucy sir";
string pronoun = " he ";
string pronoun1 = " him ";
string pronoun2 = " his ";
string pronoun3 = " he's ";
cout << "Have fun playing Insert-Name-Here!" << endl;
}
else if (gender == 2) {
string namingGender = " manseva madam";
string pronous = " she ";
string pronou1 = " her ";
string pronoun2 = " her ";
string pronoun3 = " she's ";
cout << "Have fun playing Insert-Name-Here!" << endl;
}
else if (gender == 3) {
string nammingGender = " majestic mate";
string pronoun = " they ";
string pronoun1 = " them ";
string pronoun2 = " their ";
string pronoun3 = " they're ";
cout << "Have fun playing Insert-Name-Here!" << endl;
}
else {
cout << "You did not enter 1 2 or 3...guess your other than" << endl;
string nammingGender = " majestic mate";
string pronoun = " they ";
string pronoun1 = " them ";
string pronoun2 = " their ";
string pronoun3 = " they're ";
cout << "Have fun playing Insert-Name-Here!" << endl;
}
cout << "By the way, what is your name... " << namingGender << "?" << endl;
cin >> playerName;
Run Code Online (Sandbox Code Playgroud)
问:有没有更好的方法来做到这一点或解决这个问题?
答:是的:
string namingGender;
cout << "Please enter your gender \n1. Male \n2. Female \n3. Other" << endl;
cin >> gender;
if (gender == 1) {
namingGender = " saucy sir";
...
else if (gender == 2) {
namingGender = " manseva madam";
Run Code Online (Sandbox Code Playgroud)
您所展示的是“可变阴影”的一个很好的例子。这不是你打算做的。
在 if/else 块之外“声明”;然后在每个案例的基础上“分配”。