【发布时间】:2015-01-13 05:40:05
【问题描述】:
如果没有输入参数,我需要为命令行应用程序提供默认行为。
如果没有输入任何参数,我需要程序为空终止符设置 argv[1][0] = '1' 和 argv[1][1] = '\0'。
当我尝试在 g++ 中编译我的代码时,我不断收到核心转储,这就是导致问题的原因:
int main(int argc, char * argv[]){
//for testing we put some dummy arguments into argv and manually set argc
//argc = 1;//to inlcude the program name
//we put a defualt value into argv if none was entered at runtime
if(argc == 1){
argv[1][0] = '1';
argv[1][1] = '\0';//add a null terminator to our argv argument, so it can be used with the atoi function
}
另外,我不在 C++ 11 上。
重构代码:(基本上只是围绕问题编写代码,这样我们就不必在主函数中操作 argv[])
int argvOneAsInt;
if(argc != 1){
argvOneAsInt = atoi(argv[1]);//use atoi to convert the c-string at argv[1] to an integer
}
else{
argvOneAsInt = 1;
【问题讨论】:
-
您应该将参数复制到变量并在程序中使用它们。如果没有提供参数,那么很容易设置变量。
-
如果没有提供任何参数,那么您认为
argv[1]指向什么?提示std::vector<std::string> args(argv, argv + argc);现在你可以用它做你想做的事了。 -
您需要复制一份
argv。这将允许您使用默认值。因此,将本地argv变量设为默认值,然后将argv值从main参数复制到本地argv变量中。