我必须通过使用命令行参数(argv,argc)在c ++中的函数内传递系统配置细节.该函数如下所示:
function(char * array[]){
windows_details = array[1];
graphic_card = array[2];
ram_detail = array[3];
procesor_detail = array[4];
}
int main(int argc, char *argv[]){
char *array[] = { argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]};
function(array);
}
Run Code Online (Sandbox Code Playgroud)
所以,当我按如下方式执行程序exe时,我得到正确的输出:
sample.exe windows_32bit nividia 5Gb i7processor
Run Code Online (Sandbox Code Playgroud)
但我关注的是每次值都必须按特定顺序排列,即用户必须注意"windows_details"将是第一个命令行参数,然后是"graphic_card",并且像ram_details和processor_details一样,所以这个解决方案不健壮,即如果值序列互换,结果将不正确.我希望解决方案与序列无关,无论在正确位置要替换的值的顺序,还是将值作为值传递给选项的命令行参数.例如如下:
sample.exe --configuration i7_processor 5GB windows_32bit nividia or
sample.exe --configuration 5GB i7_processor nividia windows_32bit or
sample.exe --configuration nividia windows_32bit 5GB i7_processor
.
.
Run Code Online (Sandbox Code Playgroud)
因此,像上面一样,选项为"--configuration",然后是任何序列中的详细信息.我尝试添加选项部分如下,但它不起作用:
int main(int argc, char *argv[]){
char *array[] = { argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]};
std::string arg = *(reinterpret_cast<std::string*>(&array));
if (arg == "--configuration"){
function(array);
}
else {
std::cout << "Usage " << argv[0] << "\t--config\t\t Specify the configuration of target" << std::endl;
return 1;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以,请帮我解决我的问题.我该怎么做才能使它更加强大并增加选项?
你应该使用getopt或Boost.ProgramOptions.*(reinterpret_cast<std::string*>(&array))是非常愚蠢的,并没有做你认为它做的事情.
有很多关于如何使用它们的教程.以下是getopt手册和Boost.ProgramOptions文档链接的示例
一个简单的BPO示例如下所示:
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("arch", po::value< string >(),
"Windows version")
("card", po::value< string >(),
"Graphics card")
("ram", po::value< string >(),
"Amount of RAM")
("cpu", po::value< string >(),
"Type of processor")
;
po::variables_map vm;
po::store(po::command_line_parser(ac, av).
options(desc).run(), vm);
po::notify(vm);
if (vm.count("help")) {
cout << "Usage: options_description [options]\n";
cout << desc;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果你愿意,你可以包括对位置选项的支持,但是我并不完全清楚如何在没有显式开关的情况下区分各种选项.
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |