【发布时间】:2019-07-24 18:58:10
【问题描述】:
我目前正在开发一个基于文本的冒险游戏,作为课堂项目。我几乎一切都开始了并且工作正常。唯一的问题是,当我问用户他们想换到哪个房间时,如果他们输入一个空白输入,那么应该输出一条消息说“你必须选择一个房间”。对于我的生活,我无法弄清楚。非常感谢任何帮助。
代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
bool game_play = true;
bool game_start = true;
int room_change;
int room_current = 0;
while (game_play == true) {
if (game_start == true) {
srand((unsigned int)time(NULL));
room_change = rand() % 2 + 1;
game_start = false;
}
else {
for (bool check = false; check == false;) { // Check if input is invalid
cin >> room_change;
if (cin.fail()) {
cout << "Choose an existing room.";
cin.clear();
cin.ignore();
}
else if (room_change == room_current) {
cout << "You're already in that room.";
}
else {
check = true;
}
}
}
switch (room_change) {
case 1:
cout << "You are in room 1.";
room_current = 1;
break;
case 2:
cout << "You are in room 2.";
room_current = 2;
break;
case 3:
game_play = false;
break;
default:
cout << "That room doesn't exist.";
}
}
return 0;
}
【问题讨论】:
-
不要循环调用
srandsrand() — why call it only once?
标签: c++ if-statement input integer