简体   繁体   中英

Checking if argv[i] exists C++

If I ran a C++ program

./program arg1

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

Yes, look at the value of argc :

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

Yes , argv[i] ends with NULL . argc is number of arguments passed to main function. Get an idea from following code.

#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",NULL and argc = 3.

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

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

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

Learn HEAR

The prototype of main says it all:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM