int next_option;

    const char *const short_options = "vho:";//代表可以有三种命令行参数,-v,-h,-o,o后面跟一个冒号代表-o后面需要跟参数,如 -v -h -o test

    const struct option long_options[] = { 
    {"version",0,NULL,'v'},//第一列是长参数,第二列是1代表后面需要跟参数,0代表不需要跟参数,第四列是短参数,也即-v和--version等价,-h和--help等价,-o和--output等价
    {"help",0,NULL,'h'},
    {"output",1,NULL,'o'},
    {0,0,0,0}
    };  

    while((next_option = getopt_long(argc,argv,short_options,long_options,NULL)) != -1) 
    {   
        switch(next_option)
        {   
            case 'h':
                cout<<"help"<<endl;
                break;
            case 'v':
                cout<<"this version is test"<<endl;
                break;
            case 'o':
                cout<<"output file name is "<<optarg<<endl;//optarg参数在getopt.h中已经定义,自动获取-o后面跟着的参数
                break;
        }   
    }   

    for(int i = optind;i<argc;i++)//若出现ovh之外的参数,optind记录该参数位置
    {   
        cout<<argv[i]<<" ";
    }   
    cout<<endl;

 

posted on 2014-02-11 15:12  lss1990  阅读(173)  评论(0编辑  收藏  举报