【发布时间】:2018-02-17 06:01:57
【问题描述】:
我是编程新手,正在做从这里http://www.cplusplus.com/forum/articles/12974/ 找到的编码挑战。我无法通过谷歌搜索找到我的具体问题的答案,这是我第一次在这里发帖,所以如果我违反了任何准则,我深表歉意!我正在研究让用户选择一个数字来选择他们最喜欢的饮料的挑战。
我刚刚了解了 switch 语句,我命名了 5 种情况,不包括默认情况。我试图弄清楚如何将 if 语句合并到 switch 语句中(如果这甚至可能的话),或者它可能是我正在寻找的 for 循环?我不确定,但我愿意了解它是什么。我正在尝试这样做,以便如果用户没有输入有效的案例编号并且它会进入默认状态。 (例如:1、2、3、4 或 5 以外的任何值)我希望用户在遇到默认情况时再次尝试输入正确的数字。
这是我的代码
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
int choice;
cout << "Choose your beverage of choice by number: " << endl;
cout << "1. Coke" << endl;
cout << "2. Dr. Pepper" << endl;
cout << "3. Sprite" << endl;
cout << "4. Iced Tea" << endl;
cout << "5. Water" << endl;
cout << '\n';
cin >> choice;
cout << '\n' << "Choice entered: " << choice << endl;
cout << '\n';
switch (choice)
{
case 1 : cout << "You have chosen Coke." << endl;
break;
case 2 : cout << "You have chosen Dr. Pepper." << endl;
break;
case 3 : cout << "You have chosen Sprite." << endl;
break;
case 4 : cout << "You have chosen Iced Tea." << endl;
break;
case 5: cout << "You have chosen Water." << endl;
break;
default:
cout << "Error. Choice Not valid. Money returned." << endl;
break;
}
system("pause");
return 0;
}
【问题讨论】:
-
这并没有解决问题,但是您真的需要
std::endl需要的额外内容吗?'\n'结束一行。
标签: c++ loops if-statement switch-statement