我正在尝试在终端中为C ++程序创建以下结构:
Menu:
[1] Add Number
[2] View Numbers
[3] View Average
[CHOICE 1]
- Add a Number to array
- Once finished, show Menu again so user can select another action
[CHOICE 2]
- View all numbers in array
- Once finished, show Menu again so user can select another action
[CHOICE 3]
- View average of all numbers in array
- Once finished, show Menu again so user can select another action
我不确定如何设置它。当用户输入每个菜单项的相应编号时,将显示相应的信息。这很容易,使用if语句查找用户输入的数字。
然而,当我尝试再次显示菜单以便用户可以选择其他操作时,我的问题就出现了。我认识到某种循环在这里是必要的,但我不知道该怎么做。
你能帮我建立一个如何开始的基本结构吗?我真的很感激。
答案 0 :(得分:3)
将代码分解为单独的函数:
enum Action { AddNumber, ViewNumbers, ViewAverage, Quit, Error };
Action show_menu_and_read_user_input(); // write this!
int main()
{
std::vector<int> numbers;
for (bool again = true; again; )
{
switch (show_menu_and_read_user_input())
{
case Error:
std::cout << "Sorry, I did not understand.\n";
break;
case Quit:
std::cout << "Goodbye!\n";
again = false;
break;
// ...
}
}
}
答案 1 :(得分:3)
在最基本的层面......
for(;;)
{
// Display the menu
cout << "Menu:\n"
" [1] Add Number\n"
" [2] View Numbers\n"
" [3] View Average\n";
// Ask user for input
int choice;
cin >> choice;
// Take action
if( choice == 1 ) {
// ...
} else if( choice == 2 ) {
// ...
} else if( choice == 3 ) {
// ...
} else {
cout << "Invalid choice\n";
}
}
这是一个无限循环,因为您的菜单似乎没有“退出”选项。我用if
语句而不是switch
来表达这一点,因为作为初学者,很容易被switch
弄糊涂,并且不小心会遇到问题。
一次一步=)
答案 2 :(得分:0)
将菜单条目细分为功能,以保持一切清洁,易于掌握(暂时)。
这可以扩展很多,创建某种菜单处理等,但我只是坚持这样的事情:
void mainmenu() {
int choice;
do {
std::cout << "Menu\n[1] -> Add Number\n[2] -> View Numbers\n[3] -> View Average\n[0] -> Quit" << std::endl;
std::cin >> choice;
// now perform actions based on the choice
switch (choice) {
case 1:
addanumber();
break;
case 2:
printnumbers();
break;
case 3:
printaverage();
break;
}
} while (choice); // loop as long as the choice isn't 0 (i.e. user wants to exit)
}
正如Kerrek在评论中提到的,这并不能真正检查用户是否真的选择了任何整数值。这使得代码变得更复杂,但一般来说这是一种很好的做法(因为事情扫描变得讨厌,如果你忽略了这些事情):
将上面的cin >> choice;
替换为:
if (!(std::cin >> choice)) {
choice = -1; // if input provide an invalid choice so the menu just shows again
// also clear the input buffer of leftovers
std::cin.clear(); // clear the buffer
std::cin.ignore(1000, '\n'); // read any leftover chars till a line break (user hit return key)
}