如何在不丢失数据的情况下让程序输出终止并再次启动程序?

时间:2017-04-08 12:11:24

标签: c++ switch-statement console-application

好吧所以我可能没有很好地解释这一点,但基本上我用switch语句编写了一个基于菜单的程序,我希望在选择某个选项并执行其中的所有功能后,整个程序再次启动。 这是一个举例的代码:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;



int main() {
    string name;
    int num,age,cls;
    cout <<"Enter your name: ";
    cin>>name;
    cout <<"Enter your number: ";
    cin>>num;
    cout<<"Enter your age: ";
    cin>>age;
    cout <<"Enter your class: ";
    cin>>cls;
    int choice;
    cout<<"\tPlease choose an option: "<<endl;
    cout <<"1. Display my name\n2. Display my number\n3. Display my age\n4. 
Display my class"<<endl;
    cin>>choice;
    switch (choice){
        case 1:
            cout<<"Your name is :"<<name;
            break;
        case 2:
            cout <<"Your number is: "<<num;
            break;
        case 3:
            cout <<"Your age is: "<<age;
            break;
        case 4:
            cout <<"Your class is: "<<cls;
            break;
        default:
            cout <<"Invalid option!";
            break;
    }
   return 0;
}

如何在选择选项后让程序在结束时终止,而是再次显示整个菜单以选择其他选项。或者在给出无效输入后再次显示整个菜单,并执行默认情况。

2 个答案:

答案 0 :(得分:1)

您只需添加一个while循环并支持菜单选项即可退出循环。

int main() {
    string name;
    int num,age,cls;
    cout <<"Enter your name: ";
    cin>>name;
    cout <<"Enter your number: ";
    cin>>num;
    cout<<"Enter your age: ";
    cin>>age;
    cout <<"Enter your class: ";
    cin>>cls;

    int choice;

    bool exitRequested = false;
    while ( !exitRequested )
    {
        cout<<"\tPlease choose an option: "<<endl;
        cout <<"1. Display my name\n2. Display my number\n3. Display my age\n4. Display my class\n5. Exit program"<<endl;

        cin>>choice;
        switch (choice){
            case 1:
                cout<<"Your name is :"<<name;
                break;
            case 2:
                cout <<"Your number is: "<<num;
                break;
            case 3:
                cout <<"Your age is: "<<age;
                break;
            case 4:
                cout <<"Your class is: "<<cls;
                break;
            case 5:
                exitRequested = true;
                break;
            default:
                cout <<"Invalid option!";
                break;
        }
    }
    return 0;
}

答案 1 :(得分:0)

if ~isempty(bbox);
    bbox = bbox(1,1:4);
    Ic = imcrop(im,bbox);
    bboxeye = step(faceDetectorLeye, Ic);
end

&GT;