我正在用C ++编写程序,我希望用户在几个选项之间做出选择,每个选项都不同。在选项的最后,我希望用户能够从菜单中选择不同的选项,但如果用户最初选择选项3,当用户返回菜单时,如果他/她选择1或2终止程序。我该怎么做才能使代码重复?
#include <iostream>
using namespace std;
int main() {
int play;
cout << "What do you want to do now?" << endl;
cout << "Choose a number..." << endl;
cout << "1) Talk." << endl;
cout << "2) Vent." << endl;
cout << "3) Play a guessing game." << endl;
cout << "4) End." << endl;
cin >> play;
while (play == 1){
//code here
cout << "What do you want to do now?" << endl;
cout << "Choose a number..." << endl;
cout << "1) Talk." << endl;
cout << "2) Vent." << endl;
cout << "3) Play a guessing game." << endl;
cout << "4) End." << endl;
cin >> play;
}
while (play == 2){
//code goes here
cout << "What do you want to do now?" << endl;
cout << "Choose a number..." << endl;
cout << "1) Talk." << endl;
cout << "2) Vent." << endl;
cout << "3) Play a guessing game." << endl;
cout << "4) End." << endl;
cin >> play;
}
return 0;
}
答案 0 :(得分:1)
执行此类操作的常用方法是将整个代码放在while (true)
循环中,并在用户选择退出时中断,如下所示:
#include <iostream>
using namespace std;
int main()
{
int play;
while (true)
{
cout << "What do you want to do now?" << endl;
cout << "Choose a number..." << endl;
cout << "1) Talk." << endl;
cout << "2) Vent." << endl;
cout << "3) Play a guessing game." << endl;
cout << "4) End." << endl;
cin >> play;
if (play == 1)
{
// code for Talk...
}
else if (play == 2)
{
// code for Vent...
}
else if (play == 3)
{
// code for Play a guessing game....
}
else if (play == 4)
{
// End
return 0;
}
else
{
std::cout << "Expected a number between 1 and 4" << std::endl;
}
}
}
编辑我还为无法识别的输入添加了测试 编辑如果您更喜欢语法,也可以使用switch语句(除非您真的需要,否则请确保没有掉头) (注意:两个代码都是等效的,可能会生成相同的程序集)
int main()
{
int play;
while (true)
{
cout << "What do you want to do now?" << endl;
cout << "Choose a number..." << endl;
cout << "1) Talk." << endl;
cout << "2) Vent." << endl;
cout << "3) Play a guessing game." << endl;
cout << "4) End." << endl;
cin >> play;
switch (play)
{
case 1:
// code for Talk...
break;
case 2:
// code for Vent...
break;
case 3:
// code for Play a guessing game....
break;
case 4:
// End
return 0;
default:
std::cout << "Expected a number between 1 and 4" << std::endl;
}
}
答案 1 :(得分:0)
执行此操作的一种奇特方法是使用switch()
,这里是Why the switch statement and not if-else? switch()
可以帮助您的程序摆脱非常长的嵌套if-else语句。看看它有多美:
#include <iostream>
int main()
{
int play = 0;
while (play != 4)
{
std::cout << "What do you want to do now?" << std::endl;
std::cout << "Choose a number..." << std::endl;
std::cout << "1) Talk." << std::endl;
std::cout << "2) Vent." << std::endl;
std::cout << "3) Play a guessing game." << std::endl;
std::cout << "4) End." << std::endl;
std::cin >> play;
switch (play)
{
case 1: // code for talk here
break;
case 2: // code for Vent
break;
case 3: // code for Play
break;
case 4: std::cout << "program will exits!";
}
}
return 0;
}