问题描述
我是 C++ 新手,正在尝试读取如下指定的命令行参数。
./helloworld -i input_file -o outputfile -s flag3 -t flag4
我尝试通过索引对标志进行硬编码,如下所示
int main(int argc,char *argv[]) {
// argv[1] corresponds to -i
// argv[2] corresponds to input_file
// argv[3] corresponds to -o
// argv[4] corresponds to outputfile
// argv[5] corresponds to -s
// argv[6] corresponds to flag3
// argv[7] corresponds to -t
// argv[8] corresponds to flag4
}
然后我意识到可以更改顺序所以我不能使用硬编码索引,我使用了
unordered_map
这工作正常,但我想知道有没有更好的方法来做同样的事情。
解决方法
天哪。好的,您可以手动执行此操作,我将向您展示一些代码。但是请看一下 getopt()。它已经对你有很大帮助,但需要一点时间来适应。
但这里是您手动编码的方法:
int index = 1;
while (index < argc) {
string cmnd = argv[index++];
if (cmnd == "-i") {
if (index >= argc) {
usage(); // This should provide help on calling your program.
exit(1);
}
inputFileName = argv[index++];
}
else if (cmnd == "-whatever") {
// Continue to process all your other options the same way
}
}
现在,这不是任何人这样做的方式。我们使用某些版本的 getopt()。我相信还有另一个我喜欢的叫 getopt_long。你会想要挖掘这样的东西。然后我用自己的包装器包裹所有这些,这样我就可以做一些非常酷的事情。
如果您想查看我使用的包装器:https://github.com/jplflyer/ShowLib.git 并查看 OptionHandler.h 和 .cpp。它太酷了。我认为有一个如何在某处使用它的示例。
但是你需要知道它是如何工作的,所以对于你的第一个程序,也许像我向你展示的那样手动完成。
,您可以使用 3rdparty 库来解析命令行参数。
例如:https://github.com/mirror/tclap