【发布时间】:2015-10-28 02:20:31
【问题描述】:
我正在学习 C++,这是我在 Uni 课程的一部分。我对 c++ 的经验并不丰富,但我已经搜索了几个小时的可能解决方案并测试了数百种代码变体,但我仍然无法使其正常工作。我相信我对 Enums 的使用从根本上是错误的——我从来没有让它们按我的意图工作。对于这个任务,我们必须使用 Enums 和 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 >> input;。我知道这是导致循环的原因。我曾尝试将cin>> 换成getline(cin,input)alternative,但这似乎也不起作用。
【问题讨论】:
-
复制粘贴代码到这里。 (您可能需要使用全选 -> ctrl+K 格式化代码)
-
我假设您设置为枚举的值是房间成本,而用户选择选择特定房间类型的值不在协议中。您永远不会声明枚举的变量类型,甚至在代码中使用它。在下面查看我的答案,以查看使用枚举作为选择类型的工作应用程序。价格在案例陈述中确定。此外,还会要求用户做出与枚举类型相同的选择。
标签: c++ visual-c++ enums switch-statement