如何制作用户可以选择的菜单

时间:2014-02-06 16:33:37

标签: c++

我正在尝试创建一个菜单,用户可以从选项列表中进行选择。在他们选择其中一个选项后,它会在完成后显示cout<<,我希望它循环回菜单,以便他们可以选择另一个选项..这是我的代码到目前为止。它没有完成,但我尝试了所有的东西,从使变量的那一部分...就像给它一个值的值,当它去一个选项我改变该变量,所以它不循环,但它完成后我把它放回去到1 ..但这不起作用。任何帮助将不胜感激。

#include <iostream>

using namespace std;

int main()
{
    int option=0;
    int main = 0;

    cout << "Hello there...\n\nToday we are going to do a little fun project that I created.\n\n";
    cin.get();

    cout << "\nAs we progress throughout this program, I will explain the different things\n";
    cout << "that we are going to do. We will be covering some basic C++ excersises.";
    cout << "\n\nFirst and foremost we will  begin by  covering what I have learned so far....\n\n";
    cin.get();

    cout << "The first topic we will cover will include what is known as 'variables'.\n";
    cout << "what are variables you ask?";
    cin.get();

    while (10)
    {
        cout << "\n\n\nEnter the number of one of the following and I will explain!\n";
        cout << "1.integer  2.boolian   3.floats   4.doubles   5.character";
        cout << "\n\n[when you are done type 'done' to continue]\n\n";
        cin >> option;
    }

    if (option = 1);
    {
        cout << "\nInteger is the variable abbreviated as 'int' this allows C++ to only";
        cout<<"\nreadwhole and real numbers \n\n";
    }



}

3 个答案:

答案 0 :(得分:2)

您希望在您设置的while循环中拥有所有菜单逻辑。您拥有的当前while (10)条件应该会导致无限循环;这可能是您当前版本无法正常工作的原因。我会尝试修改你的while循环:

while (option != -1) // put whatever your loop exit condition is here
{
    cout << "\n\n\nEnter the number of one of the following and I will explain!\n";
    cout << "1.integer  2.boolian   3.floats   4.doubles   5.character";
    cout << "\n\n[when you are done type 'done' to continue]\n\n";
    cin >> option;

    if (option == 1)
    {
        cout << "\nInteger is the variable abbreviated as 'int' this allows C++ to only";
        cout<<"\nreadwhole and real numbers \n\n";
    }
}

答案 1 :(得分:1)

如果您想支持"done",请将输入保存在字符串中,然后使用std::stoi将其转换为int。使用switch代替一堆ifwhile(true)继续使用,直到使用break关键字。

std::string in;
int op = 0;

while (true)
{
  // PRINT OPTIONS
  // GET INPUT

  if (in == "done") break;

  switch (std::stoi(in))
  {
    case 1:
      // OPTION 1
    break;
    case 2:
      // OPTION 2
    break;
    default:
      // INVALID OPTION
    break;
  }
}

答案 2 :(得分:0)

使用do while控制流程块并检查使程序结束的特定输入。

例如,您可以像这样更改程序的主要结构:

int flag = 1;
char c = 'a';
do {
    cout << "SHOW THE MENU " << endl;
    cout << "press 'x' to exit" << endl;
    cin>>c;

    if(c == '1')
    {
        cout << "doing 1" << endl;
    } 
    else if (c == '2') 
    {
        cout << "doing 2" << endl;
    }
}  while(c != 'x');