我正在创建一个简单的c++主机游戏,你可以在其中输入一系列命令,赚钱和购买东西。当我在前几个命令中编码时,我得到了一个错误,说我缺少一个";"前"}";在第37行。我每行都以分号结束,我似乎不明白问题所在。我在第37行加上了星号。下面是我的代码:
using namespace std;
void starting() {
cout << "***********DANK MEMER***********" << endl;
cout << "Enter Your Command: ";
}
int main()
{
starting();
int balance = 0;
bool hasShovel = false;
string command;
do {
cin >> command;
// /help
if (command == "/help") {
cout << "The list of commands are n /buy shovel n /buy lawnmower n /sell
shovel n /sell lawnbower n /luck n n /exit /rob n /balance n /invest n /dig n
/mow" << endl;
}
// buy shovel
else if (command == "/buy shovel") {
// checking if they have enough balance
if (balance > 100) {
cout << "You don't have enough to buy a shovel. It costs 100 memers." <<
endl;
}
*****************************************
// giving them the shovel
else {
balance -= 100;
hasShovel = true;
cout << "You have a shovel now. Happy digging!" << endl;
}
}
else {
cout << "BRUH! Not a valid command";
}
} while (command != "/exit");
}
在https://www.onlinegdb.com/online_c++_compiler中运行代码会发现问题。在字符串文本的第24行中有一个新行。换行符如果没有转义(),有时会引起麻烦。
试着这样写:
if (command == "/help") {
cout << "The list of commands are n /buy shovel n /buy lawnmowern"
"/sell shoveln"
"/sell lawnbowern"
"/luck n n"
"/exit /rob n"
"/balance n"
"/invest n"
"/dig n"
"/mow" << endl;
预处理器将连接单个字符串段,不带任何空格,但这就是n
的作用。
这段代码对我来说编译得很好:
#include <iostream>
#include <string>
using namespace std;
void starting() {
cout << "***********DANK MEMER***********" << endl;
cout << "Enter Your Command: ";
}
int main()
{
starting();
int balance = 0;
bool hasShovel = false;
string command;
do {
cin >> command;
// /help
if (command == "/help") {
cout << "The list of commands are n /buy shovel n /buy lawnmowern"
"/sell shoveln"
"/sell lawnbowern"
"/luck n n"
"/exit /rob n"
"/balance n"
"/invest n"
"/dig n"
"/mow" << endl;
}
// buy shovel
else if (command == "/buy shovel") {
// checking if they have enough balance
if (balance > 100) {
cout << "You don't have enough to buy a shovel. It costs 100 memers." << endl;
}
// giving them the shovel
else {
balance -= 100;
hasShovel = true;
cout << "You have a shovel now. Happy digging!" << endl;
}
}
else {
cout << "BRUH! Not a valid command";
}
} while (command != "/exit");
}