菜单驱动器输入执行循环

时间:2017-02-18 05:23:01

标签: c++

我需要为我的编程类创建一个菜单驱动输入[Case / Switch Statement]。我的教授没有教我们如何创建一个菜单,我很难理解我的教科书。我需要循环菜单,直到用户选择退出以终止程序。我还需要一个错误消息,其中包含Case / Switch中的默认值,错误消息必须描述错误 由用户引起。

任何人都可以指导我做什么吗?我只需要开始,其余的通常是我自然而然的。

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

ofstream ofs("bafia_lab5.txt");

string msg = "eofmessage ";
string cno = "blank ";
string name = "blank ";
string dat = "2/16/17 ";
string lab = "blank ";
string phn = "blank ";
string sum = "Create  menu that allows users to choose between While Loop, Do Loop, For Loop and quit. ";
string whlo = "While Loop:";
string dooo = "Do While Loop:";
string forro = "For While Loop";
int counter;
int option;

//Header for lab with name, class#, due date, and lab number
void hdr()
{
    ofs << name << cno << dat << lab << endl;
    ofs << endl;
}

void menu()
{
    do 
    {
        ofs << "1. Do Loop " << dooo << endl;
        ofs << "2. While Loop " << whlo << endl;
        ofs << "3. For Loop" << forro << endl;
        ofs << "4. Quit " << endl;
        ofs << endl;
    } while (option <= 4)
}


//Function for "while loop"
void whl()
{
    ofs << whlo << endl;
    counter = 1;

    while (counter <= 10)
    {
        ofs << counter << endl;
        counter++;
    }
    ofs << endl;
}

//Function for "do while loop"
void doo()
{
    ofs << dooo << endl;
    counter = 1;

    do
    {
        ofs << counter << endl;
        counter++;
    } while (counter <= 10);
    ofs << endl;
}

//Function for "for loop"
void forr()
{
    ofs << forro << endl;
    for (counter = 1; counter <= 10; counter++)
    {
        ofs << counter << endl;
    }
    ofs << endl;
}

//Function for description of lab
void ftr()
{
    ofs << sum << endl;
    ofs << endl;
}

//End of file function with name, class#, due date, and lab number
void eof()
{
    ofs << msg << name << cno << dat << lab << endl;
}

//Call all functions
int main()
{
    hdr();
    menu();
    whl();
    doo();
    forr();
    ftr();
    eof();
    return 0;
}

1 个答案:

答案 0 :(得分:2)

您可以这样做:

char choice = 'y';
while(choice == 'y' || choice == 'Y'){
    cout << "Enter choice : ";
    cin >> choice;
    switch(choice) {
         case 'a' : cout << "This is case-a\n";
                    //do something
                    break;
         ...
         default : //invalid choice alert
                    break;
    }
    cout << "Enter y/Y to continue else anything else to exit : ";
    cin >> choice;
}