你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

cmdline案例2

2021/12/20 22:38:55

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;
}