由于您使用的是 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-或否)
编辑(注意 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]) );