cmdline案例2

cmdline托管在github仓库:这里
案例一在:这里,介绍很详细了,不再赘述
希望读者能先去看案例一,下面是对仓库中test2.cpp的解释

#include "cmdline.h"

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
  //initialize a parser
  cmdline::parser a;

  //add arguments
  a.add<string>("host", 'h', "host name", true, "");
  a.add<int>("port", 'p', "port number", false, 80, cmdline::range(1, 65535));
  a.add<string>("type", 't', "protocol type", false, "http", cmdline::oneof<string>("http", "https", "ssh", "ftp"));
  a.add("help", 0, "print this message");

  
  //add foot note in the usage line
  a.footer("filename ...");


  //the default programe name is the .exe file's name, here we can reset it      
  a.set_program_name("test");


  //run the parser, every argument should be set before this line
  bool ok=a.parse(argc, argv);


  //if there is only one word, only the command word, or option 'help' is considered, 
  //the programe will terminated, an usage message will pop up.
  if (argc==1 || a.exist("help")){
    cerr<<a.usage();
    return 0;
  }


  // print the argc num, which equals to the commandline length.
  cout << argc << endl;


  // If the parser process has an error, print the error message with a usage message.
  if (!ok){
    cerr<<a.error()<<endl<<a.usage();
    return 0;
  }
  // print the arguments
  cout<<a.get<string>("host")<<":"<<a.get<int>("port")<<endl;
  cout << a.get<string>("type") << endl;


  // If one argument was taken in after no option, it will be assigned to a.rest()
  for (size_t i=0; i<a.rest().size(); i++)
    cout<<"- "<<a.rest()[i]<<endl;

  return 0;
}


下面这段代码用来测试argc,容易发现argc就是命令行中单词的个数

#include "cmdline.h"

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
  //initialize a parser
  cmdline::parser a;

  //add arguments
  a.add<string>("host", 'h', "host name", true, "");
  //a.add<int>("port", 'p', "port number", false, 80, cmdline::range(1, 65535));
  //a.add<string>("type", 't', "protocol type", false, "http", cmdline::oneof<string>("http", "https", "ssh", "ftp"));
  a.add("help", 0, "print this message");

  
  //add foot note in the usage line
  a.footer("filename ...");


  //the default programe name is the .exe file's name, here we can reset it      
  a.set_program_name("test");


  //run the parser, every argument should be set before this line
  bool ok=a.parse(argc, argv);

  cout << argc << endl;
  //
  if (argc==1 || a.exist("help")){
    cerr<<a.usage();
    return 0;
  }
  



  if (!ok){
    cerr<<a.error()<<endl<<a.usage();
    return 0;
  }

  /*cout<<a.get<string>("host")<<":"<<a.get<int>("port")<<endl;
  cout << a.get<string>("type") << endl;*/

  for (size_t i=0; i<a.rest().size(); i++)
    cout<<"- "<<a.rest()[i]<<endl;

  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值