我目前正在从事基于文本的冒险游戏,作为课堂项目。我几乎一切都开始了,并且工作正常。唯一的问题是,当我问用户要更改到哪个房间时,如果他们输入空白,则应该输出一条消息,说“您必须选择一个房间”。对于我的一生,我无法弄清楚。非常感谢您的帮助。
代码:
#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;
}
答案 0 :(得分:2)
我只是运行您的代码,当您按Enter键时,它将一直等待,直到您输入数字或无效字符(例如字符或字符串)为止。我确实发现,如果您从以下位置更改代码
cin >> room_change;
到
cin >> noskipws >> room_change;
当用户输入空白时,它将使cin.fail()返回true,然后继续打印“选择现有房间”。
在您的情况下,while循环将一直被调用,直到我们获得有效的输入为止。确实会重复“选择现有房间”,因为room_change是一个整数,因此当我们按Enter键时,'\ n'将保留在缓冲区中。然后,下一次迭代的while循环将读取'\ n'并执行cin.fail(),然后再输入其他内容。我发现的一种解决方案是使用更多的cin.ignore()语句。
for (bool check = false; check == false;) { // Check if input is invalid
cin >> noskipws >> 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.";
cin.ignore();
} else {
check = true;
cin.ignore();
}
}
原因是因为我们要摆脱该'\ n',以便cin.fail()不执行。但是,我确实发现,当您输入一个字符时,它将两次打印“选择现有房间”。因为字符不是整数,它将第一次打印,并且由于该字符'\ n',它将第二次打印。
答案 1 :(得分:0)
唯一的问题是,当我问用户要更改到哪个房间时,如果他们输入空白,则应该输出一条消息,说“您必须选择一个房间。”
使用std::getline
,然后使用std::istringstream
从行中提取数字是一种更好的策略。
std::string line;
std::cout << "Choose an existing room. ";
while ( std::getline(std::cin, line) )
{
// Try to get the room_change using istringstream.
std::istringstream str(line);
if ( str >> room_change )
{
// Successfully read the room.
break;
}
// Problem reading room_change.
// Try again.
std::cout << "Choose an existing room. ";
}
答案 2 :(得分:0)
#include <iostream>
using namespace std;
int main(){
int room_change=200;
cout<<"Enter Blank";
cin>>room_change;
if(room_change==NULL){
cout<<"There is NO-THING"<<endl;
}
if(room_change!=NULL){
cout<<"There is something and that is :"<<room_change<<endl;
}
return 0;
}
但是更简单的方法是使用字符串。如果这是一种家庭作业,并且您仅限于Integer变量。如果要检测Buffer是否为空,则要复杂得多。无论作业有什么限制,OS层输入都是基于字符串的。 How can I use cin.get() to detect an empty user input?