Question

I have the below code which compiles however I would like it to loop back to the original menu after the user has selected a choice so another can be picked.

Any help would be greatly appreciated.

#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
    int choice;
    cout<<"Select your favourite soft drink:\n";
    cout<<"Pepsi - 1\n";
    cout<<"sprite - 2\n";
    cout<<"fanta - 3\n";
    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;
}
Was it helpful?

Solution

#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 - 1\n";
    cout<<"sprite - 2\n";
    cout<<"fanta - 3\n";
      cout<<"exit - 4\n"; // <-- 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;
}

OTHER TIPS

#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
    int choice;
    do{ //Start Loop

        cout << "Select your favourite soft drink:\n";
        cout << "Pepsi - 1\n";
        cout << "sprite - 2\n";
        cout << "fanta - 3\n";
        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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top