令人困惑的c++循环

Confusing C++ Loops

本文关键字:c++ 循环      更新时间:2023-10-16

我正在尝试为终端中的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)
}