C++ 更改命令行参数argv
我想修改或删除C++ 更改命令行参数argv,c++,command-line,argv,argc,C++,Command Line,Argv,Argc,我想修改或删除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
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
//在main()顶部附近的某个地方
bool itemFound(false);
对于(inti=1;i您是否尝试过调试?如果尝试过,您将看到它从不尝试擦除任何内容。
您不能将字符串(char*
)与简单相等进行比较,因为实际上您是在比较指针,指针(几乎)永远不会相等。相反,您应该使用字符串比较函数,如下所示:
if (!strcmp(argv[i], "--item")) {
此外,由于要覆盖参数,不需要使用大量空格,只需将其设置为空字符串(argv[i]=“”
),或修改现有字符串使其为空(argv[i][0]=0
)或者,您可以转换其余的参数,这样就不会有可能混淆您剩余代码的空隙。 < P>因为您使用C++,您可以将所有类似于C的字符串转换为STD::String。因为该操作在程序开始时执行一次,所以没有效率问题。
//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
//在main()顶部附近的某个地方
bool itemFound(false);
对于(int i=1;i)
编辑(注意std::string和char*之间是否存在比较运算符)
bool itemFound(false);
对于(inti=1;iuse strcpy(argv[i],“”),如果要直接使用参数,我会首先将参数复制到某种数据结构中。否则Nishith的解决方案可能会起作用std::vector args(argv,argv+argc)是的,那当然是我的问题。谢谢。正如我写的,这个测试非常混乱,因为strcmp
返回一个int
,而不是bool
。如果(strcmp(argv[i],“--item”)==0
,那就更好了。另外,根据C标准,argv[i]=“
是未定义的行为。(C++标准没有说明你是否可以修改<代码> ARGV[i],[Case>或者不,但是这里有一个C兼容性。)我不知道为什么这个限制,我从来没有听说过一个系统,它实际上会引起问题,但是C标准明确地说它是被禁止的。有趣的是,虽然我不能确定它是什么。“更好”
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);
}
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]) );