我正在尝试用C ++制作我的第一个文本到游戏。唯一的问题是我的代码中的默认语句使游戏出现故障。我正在尝试使用另一个名为exceptionHandler的函数来处理默认语句,但它似乎并没有起作用。有什么建议?这是代码:
#include <iostream>
#include <cstdlib>
using namespace std;
void space(), menu(), exceptionHandler();
int back1, back2;
int main()
{
cout << "Siddiqui Interactive presents..." << endl;
cin.get();
system("CLS");
cout << "Outland" <<endl;
cin.get();
int bob = 0;
//to loop back to main menu
while(bob < 5){
system("CLS");
cout << "Outland" <<endl;
space();
cout << "Press 1 to begin" <<endl;
cout << "Press 2 for credits" <<endl;
cout << "Press 3 to quit" <<endl;
int switch1;
cin >> switch1;
switch(switch1){
case 1:
//nothing here for now
break;
case 2:
system("CLS");
menu();
if(back1 == 1){
system("CLS");
//clears screen to loop back to the menu
}
break;
case 3:
return 0;
break;
default:
system("CLS");
exceptionHandler();
}
}
return 0;
}
void menu(){
//to create a function for the menu, saves time
cout << "This game was coded by: Shahmir Siddiqui and Ibrahim" <<endl;
cout << "Outland was designed by: Azmir Siddiqui" <<endl;
space();
cout << "Press 1 to go back" <<endl;
cin >> back1;
}
void space(){
//just saves time
cout << "" <<endl;
}
void exceptionHandler(){
//to handle exceptions or errors
system("CLS");
cout << "Invalid!" <<endl;
space();
cout << "Press 1 to go back" <<endl;
cin >> back2;
if(back2 == 1){
system("CLS");
//also clears screen to loop back to main menu
}
}
编辑:让我们说,我输入的是d而不是1,它只是在错误屏幕和主菜单之间继续波动。
答案 0 :(得分:1)
cin >> switch1
尝试读取整数。如果您输入d
(无法将其转换为int
,则不会输入错误输入,因此您必须手动清除它。< / p>
尝试将此添加到您的错误案例中:
cin.clear();
cin.ignore(INT_MAX, '\n');