控制台菜单

来源:互联网 发布:硅基生命 知乎 编辑:程序博客网 时间:2024/05/21 04:21
菜单是程序中获得用户输入的有效手段。
在控制台环境中菜单也能发挥重要作用。
本程序的目的是要实现一个动态菜单,即:菜单的级次、内容不是固定的,而是定义在a.txt文件中。
程序读入该文件,在内存中动态构建菜单项间的关系,然后运行该菜单。

注意:a.txt中的空白是Tab(制表符),不是空格。

                

控制台输入




#include<iostream>#include<fstream>#include<string>using namespace std;struct Jgt{    char ch[20];    struct Jgt *brother,*child,*father;};int f(char ch[])//得到每行的制表符个数{    int i=0;    while(ch[i]=='\t')i++;    return i;}void h(char ch1[],char ch2[],int m)//辅助字符串{    int i=m;    while(ch2[i]!='\0')    {        ch1[i-m]=ch2[i];        i++;    }    ch1[i-m]='\0';}/*void g(struct Jgt *p)//便利每个节点{    if(p->father)cout<<p->father->ch<<"\t";    cout<<p->ch<<endl;    if(p->child)g(p->child);    if(p->brother)g(p->brother);}*/int main(){    ifstream file("a.txt");    struct Jgt *jgt=new struct Jgt();    char ch[100];    file.getline(ch,100);    strcpy(jgt->ch,ch);    jgt->child=jgt->brother=jgt->father=NULL;    struct Jgt *p=jgt;    int i=0;    while(file.getline(ch,100))    {        struct Jgt *q=new struct Jgt();        q->child=q->brother=q->father=NULL;        int j=f(ch);        h(q->ch,ch,j);        if(j==i+1)        {            p->child=q;            q->father=p;        }        else        {            while(i>j)            {                p=p->father;                i--;            }            p->brother=q;            q->father=p->father;        }        i=j;        p=q;    }    p=jgt;    //g(p);    while(p)    {         i=1;        struct Jgt *q=p;        cout<<"-----------"<<endl;        while(p)        {            cout<<i++<<"."<<p->ch<<endl;            p=p->brother;        }        cout<<i<<".上一层"<<endl;         cout<<"-----------"<<endl;        cout<<"请输入:";        int n;        cin>>n;        if(n==i)p=q->father;        else        {            while(n-->1)q=q->brother;            p=q->child;        }    }    system("pause");    return 0;}


0 0
原创粉丝点击