我想修改或删除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
。
最好的方法是什么?
你试过调试吗?如果您这样做,您将看到它从不尝试擦除任何内容。你不能用简单的相等来比较字符串(char*
),因为在现实中你比较的是指针,它们(几乎)永远不会相等。相反,你应该使用字符串比较函数,像这样:
if (!strcmp(argv[i], "--item")) {
另外,由于您正在覆盖参数,因此不需要使用很多空格,您可以简单地将其设置为空字符串(argv[i] = ""
),或者修改现有字符串使其为空(argv[i][0] = 0
)。或者,您可以移动其余的参数,这样就不会出现可能混淆其余代码的空白。
由于您使用的是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)
Edit(考虑存在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]) );