C++循环菜单

C++ looping a menu

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

我有下面的代码可以编译,但我希望它在用户选择一个选项后循环回原始菜单,以便可以选择另一个选项。

如有任何帮助,我们将不胜感激。

#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
    int choice;
    cout<<"Select your favourite soft drink:n";
    cout<<"Pepsi - 1n";
    cout<<"sprite - 2n";
    cout<<"fanta - 3n";
    cin>>choice;
    if(choice==1)
    {
        cout<<"Good Choice"<<endl;
    }
    else if(choice==2)
    {
        cout<<"Not bad"<<endl;
    }
    else if(choice==3)
    {
        cout<<"ew!"<<endl;
    }
    getch();
    return 0;
}
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
  for(;;){ // <-- loop started here
    int choice;
    cout<<"Select your favourite soft drink:n";
    cout<<"Pepsi - 1n";
    cout<<"sprite - 2n";
    cout<<"fanta - 3n";
      cout<<"exit - 4n"; // <-- break the loop with a 4
    cin>>choice;
    if(choice==1)
    {
    cout<<"Good Choice"<<endl;
    }
      else if(choice==2)
      {
        cout<<"Not bad"<<endl;
      }
      else if(choice==3)
      {
         cout<<"ew!"<<endl;
      }
      else if(choice==4)
      {
         break;
      }    
  } // <-- loop end here
  getch();
  return 0;
}
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
    int choice;
    do{ //Start Loop
        cout << "Select your favourite soft drink:n";
        cout << "Pepsi - 1n";
        cout << "sprite - 2n";
        cout << "fanta - 3n";
        cin >> choice;
        if (choice == 1)
        {
            cout << "Good Choice" << endl;
        }
        else if (choice == 2)
        {
            cout << "Not bad" << endl;
        }
        else if (choice == 3)
        {
            cout << "ew!" << endl;
        }
    } while (choice != 4); // Keep looping until the input is 4.
    return 0;
}