[英]C++ Parse command line parameters and bool
So, I'm trying to add something that allows me to use argv to allow three command line inputs. 因此,我正在尝试添加一些允许我使用argv的内容,以允许三个命令行输入。
such that: 这样:
./program input.dat (string input)
so that (I assume) argv[0] = input.dat
and argv[1] = string input
, argue[2] = file output
因此(我假设)
argv[0] = input.dat
和argv[1] = string input
, argue[2] = file output
...I'm not sure if I'm explaining it right, but this is my best effort. ...我不确定我的解释是否正确,但这是我的最大努力。 what I want to do is have a command line input that allows me to have like, if it says "encrypt" it makes a bool true, and if I type "decrypt" it sets that bool to false.
我想要做的是有一个命令行输入,让我可以喜欢,如果它说“ encrypt”,则使布尔值为true,如果我输入“ decrypt”,则将bool设置为false。
bool encrypt;
std::string action(argv[2]);
if (action == "encrypt") {
encrypt = true;
} else if (action == "decrypt") {
encrypt = false;
} else {
// Report invalid argument
}
To do what you're describing: 执行您要描述的内容:
int main(int argc, char** argv) {
if (argc < 3) {
// print usage here and return, since that's what you need.
}
const char* filename = argv[1];
if (!strcmp(argv[2], "encrypt")) {
// encrypt!
}
else if (!strcmp(argv[2], "decrypt")) {
// decrypt!
}
else {
// error!
}
}
Or alternatively with strings: 或者使用字符串:
std::string filename = argv[1];
std::string mode = argv[2];
if (mode == "encrypt") {
// etc.
}
You can have lots of args, There's nothing to stop you from calling: 您可以有很多args,没有什么可以阻止您调用:
./program hi everybody this is a little excessive but just an example
At which point, you'd get called with argc == 12
and, eg, argv[5]
pointing to `"a"``. 此时,您将使用
argc == 12
调用,例如argv[5]
指向““ a”``。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.