C++传入命令行参数

参考:

https://blog.csdn.net/qq_34719188/article/details/83788199

https://www.man7.org/linux/man-pages/man3/getopt.3.html

 

#include <getopt.h>
#include <iostream>

int num = -1;
bool is_beep = false;
float sigma = 2.034;
std::string write_file = "default_file.txt";

void PrintHelp()
{
    std::cout <<
            "--num <n>:           Set number of program\n"
            "--beep:              Beep the user\n"
            "--sigma <val>:       Set sigma of program\n"
            "--writeFile <fname>: File to write to\n"
            "--help:              Show help\n";
    exit(1);
}

void ProcessArgs(int argc, char** argv)
{
    const char* const short_opts = "n:bs:w:h";
    const option long_opts[] = {
            {"num", required_argument, nullptr, 'n'},
            {"beep", no_argument, nullptr, 'b'},
            {"sigma", required_argument, nullptr, 's'},
            {"writeFile", required_argument, nullptr, 'w'},
            {"help", no_argument, nullptr, 'h'},
            {nullptr, no_argument, nullptr, 0}
    };

    while (true)
    {
        const auto opt = getopt_long(argc, argv, short_opts, long_opts, nullptr);

        if (-1 == opt)
            break;

        switch (opt)
        {
        case 'n':
            num = std::stoi(optarg);
            std::cout << "Num set to: " << num << std::endl;
            break;

        case 'b':
            is_beep = true;
            std::cout << "Beep is set to true\n";
            break;

        case 's':
            sigma = std::stof(optarg);
            std::cout << "Sigma set to: " << sigma << std::endl;
            break;

        case 'w':
            write_file = std::string(optarg);
            std::cout << "Write file set to: " << write_file << std::endl;
            break;

        case 'h': // -h or --help
        case '?': // Unrecognized option
        default:
            PrintHelp();
            break;
        }
    }
}

int main(int argc, char **argv)
{
    ProcessArgs(argc, argv);
    return 0;
}

/*
$ g++ -std=c++11 opt.cpp 

$ ./a.out --help
--num <n>:           Set number of program
--beep:              Beep the user
--sigma <val>:       Set sigma of program
--writeFile <fname>: File to write to
--help:              Show help

$ ./a.out --num 10
Num set to: 10

$ ./a.out --num 10 --writeFile haha.txt --sigma 3.45 --beep
Num set to: 10
Write file set to: haha.txt
Sigma set to: 3.45
Beep is set to true
*/

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值