令人困惑的c++循环
Confusing C++ Loops
我正在尝试为终端中的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语句查找用户输入的数字。
然而,当我试图再次显示菜单以便用户可以选择另一个操作时,我的问题来了。我知道这里需要某种循环,但我不确定如何进行。
你能帮我建立一个如何开始这个的基本结构吗?我真的很感激。
将代码分解为单独的函数:
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;
// ...
}
}
}
在最基本的层面上…
for(;;)
{
// Display the menu
cout << "Menu:n"
" [1] Add Numbern"
" [2] View Numbersn"
" [3] View Averagen";
// Ask user for input
int choice;
cin >> choice;
// Take action
if( choice == 1 ) {
// ...
} else if( choice == 2 ) {
// ...
} else if( choice == 3 ) {
// ...
} else {
cout << "Invalid choicen";
}
}
这是一个无限循环,因为你的菜单似乎没有"退出"选项。我已经列出了if
语句,而不是switch
,因为作为一个初学者,很容易被switch
弄糊涂,并意外地以问题结束。
一步一步来=)
将菜单条目分解为函数,以保持所有内容干净且易于掌握(目前)。
这可以扩展很多,创建某种菜单处理等,但我只坚持这样的东西:
void mainmenu() {
int choice;
do {
std::cout << "Menun[1] -> Add Numbern[2] -> View Numbersn[3] -> View Averagen[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)
}
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 在基于范围的for循环中使用结构化绑定声明
- 用于C++中带有数组和指针的循环
- 循环中的随机函数
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 在循环C++中指定字符串之后,不会打印该字符串