检查 argv[i] 是否存在 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13600204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:31:38  来源:igfitidea点击:

Checking if argv[i] exists C++

c++inputmain

提问by thisiscrazy4

If I ran a C++ program

如果我运行一个 C++ 程序

./program arg1

argv[1] exists, however is there a way to check if argv[2] exists?

argv[1] 存在,但是有没有办法检查 argv[2] 是否存在?

回答by NPE

Yes, look at the value of argc:

是的,看看 的值argc

if (argc > 2) {
  ... use argv[2] ...
}

回答by Grijesh Chauhan

Yes, argv[i]ends with NULL. argcis number of argumentspassed to main function. Get an idea from following code.

是的argv[i]NULL. argcnumber of arguments传递给主函数。从以下代码中获取想法。

#include<stdio.h>
int main(int argc, char* argv[]){
    int i=0;
    while(argv[i]!=NULL){
        printf("\n %s is argv %d ",argv[i],i);
            i++;
    }

    printf("\n");
}

desktop:~$ gcc main.c  -o main 
desktop:~$ ./main grijesh thisiscrazy4

   ./main is argv 0 
    grijesh is argv 1
    thisiscrazy4 is argv 2

here argv was - "./main","grijesh","thisiscrazy4",NULLand argc = 3.

这里 argv 是 -"./main","grijesh","thisiscrazy4",NULL并且 argc = 3。

argv[0]is executable name (path of execution) can be use to pint with error statements.
argvcalled argument vector and argccalled argument counter. you can use other variable name also.

argv[0]是可执行名称(执行路径)可用于品脱错误语句。
argv称为参数向量,argc称为参数计数器。您也可以使用其他变量名称。

Read about full syntax of main() functionthat also includes environment variables.

阅读包含环境变量的 main() 函数的完整语法

int main (int argc, char *argv[], char *envp[])
{
  return 0;
}

Learn HEAR

学习聆听

回答by Abhineet

The prototype of mainsays it all:

的原型main说明了一切:

int main(int argc, char **argv);

The first parameter here, argccarries the value of Number_Of_Arguments(argv[])_Present

这里的第一个参数,argc携带值Number_Of_Arguments(argv[])_Present

回答by Mahesh

You can try the other way around. Test the count of argc, there by you can know the presence of argv[n].

你可以换个方式试试。测试计数argc,通过你可以知道的存在argv[n]