我想修改或删除argv
中的命令行参数。
//Somewhere near the top of main()
bool itemFound(false);
for(int i=1; i<argc; ++i) {
if(argv[i] == "--item") {
itemFound = true;
//And remove this item from the list
argv[i] = " "; //Try to remove be just inserting spaces over the arg
}
}
//Now, use argc/argv as normal, knowing that --item is not in there
但是,--item
仍包含在列表中。
最好的方法是什么?
答案 0 :(得分:3)
你试过调试吗?如果你这样做,你会发现它从不试图删除任何东西。
你不能将字符串(char*
)与简单的相等进行比较,因为实际上你正在比较指针,它们(几乎)永远不会相等。相反,您应该使用字符串比较函数,如下所示:
if (!strcmp(argv[i], "--item")) {
此外,由于您要覆盖参数,因此不需要使用大量空格,只需将其设置为空字符串(argv[i] = ""
),或修改现有字符串即可空(argv[i][0] = 0
)。或者,您可以移动其余参数,这样就不会出现可能会混淆其余代码的间隙。
答案 1 :(得分:1)
由于您使用的是C ++,因此可以在std :: string中转换所有类似C的字符串。由于此操作在程序开始时完成一次,因此没有效率问题。
//Somewhere near the top of main()
bool itemFound(false);
for(int i=1; i<argc; ++i) {
if(std::string(argv[i]) == std::string("--item") ) {
itemFound = true;
//And remove this item from the list
argv[i][0] = 0; //Transform it in an empty string, putting null as first character
}
}
//Now, use argc/argv as normal, knowing that --item is not in there
否则(避免使用argv进行黑客攻击):
std::vector<std::string> validArgs;
validArgs.reserve(argc); //Avoids reallocation; it's one or two (if --item is given) too much, but safe and not pedentatic while handling rare cases where argc can be zero
for(int i=1; i<argc; ++i) {
const std::string myArg(argv[i]);
if(myArg != std::string("--item") )
validArgs.push_back(myArg);
}
如果由于任何原因你还需要itemFound,你可以在if块中设置它。
(注意:当你有一个带有单个语句的块时你不需要大括号,虽然这是一个激烈的主题:) https://softwareengineering.stackexchange.com/questions/16528/single-statement-if-block-braces-or-no)
编辑(注意std :: string和char *之间存在比较运算符)
bool itemFound(false);
for(int i=1; i<argc; ++i) {
if(std::string("--item") == argv[i] ) {
itemFound = true;
//And remove this item from the list
argv[i][0] = 0; //Transform it in an empty string, putting null as first character
}
}
或:
std::vector<std::string> validArgs;
validArgs.reserve(argc); //Avoids reallocation; it's one or two (if --item is given) too much, but safe and not pedentatic while handling rare cases where argc can be zero
for(int i=1; i<argc; ++i)
if(std::string("--item") != argv[i] )
validArgs.push_back(std::string(argv[i]) );