我正在学习 C++ 作为我在 Uni 类(class)的一部分。我在 C++ 方面经验不足,但我已经搜索了几个小时的可能解决方案并测试了数百种代码变体,但我仍然无法正常工作。我相信我对枚举的使用从根本上是错误的——我从来没有让它们按照我的预期工作。对于此任务,我们必须使用枚举和 switch 语句。
#include <iostream>
using namespace std;
enum roomType { Deluxe = 250, Twin = 150, Single = 110};
int temp;
int total;
int input = 1; int yes = 1; int no = 0;
void GetInput()
{
cin >> input;
temp = temp*input;
}
int main()
{
if (input != 0)
{
cout << "\nRoom Price Code\n------------------------------------\nDeluxe Room " << "\x9C" << "200 D\nTwin Room " << "\x9C" << "150 T\nSingle " << "\x9C" << "110 S\n\n";
cout << "Enter room type:";
GetInput();
switch (input) {
case Deluxe:
temp = Deluxe;
break;
case Twin:
temp = Twin;
break;
case Single:
temp = Single;
break;
default:
//prevents infinite loop bug
system("pause");
cout << "Entry not recognized";
main();
break;
}
cout << "\nEnter number of rooms:";
GetInput();
cout << "\nEnter number of nights:";
GetInput();
total = total + temp;
cout << "\n\x9C" << total << "\n";
cout << "More rooms? yes/no: ";
cin >> input;
main();
}
cout << "Discount? yes/no: ";
GetInput();
if (input = 1)
{
total = ((total / 100) * 75);
cout << "\n\x9C" << total << "\n";
}
cout << "your total is "<<"\x9C" << total;
system("pause");
system("cls");
return 0;
}
如果用户输入房间类型,例如 Deluxe,case 语句总是默认,然后如果没有 system("pause");
将继续陷入循环。
出于某种原因,程序似乎忽略了第一个之后的所有 cin >> 输入;
。我知道这是导致循环的原因。我曾尝试将 cin>>
换成 getline(cin,input)
替代方案,但这似乎也不起作用。
最佳答案
刚刚编译了你的代码。你没有为 Delux 做错任何事。只是愚蠢的错误,枚举值为 250 而你显示的是 200。所以在运行时,你输入 200 并且它变为默认值。
第二个问题,为什么程序只运行一次,这是因为你想要那样。检查 if (input != 0)
检查输入类型是否为整数值。您可能在命令行中输入"is",但没有进行任何错误检查。尝试输入整数值。
PS:以后请自行粘贴问题代码。
关于c++ - 枚举和开关 block 哪里出错了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33381846/