Search code examples
c++argvargc

How to check if an argument was given or not?


//Checks if an argument was specified
if (argv[1] != "")
    strcpy(Buff1, argv[1]);
else
    strcpy(Buff1, "default");

If I run: ./program test

Buff1 = test

If I run: ./program

Buff1 = PACKAGES/=packages

How do I make it if nothing was specified, that Buff1 would be "default" by default?


Solution

  • Use argc to determine arguments count. It will be equal to 1 if no arguments were given, and 2 if one argument was given.

    Note that you can't compare C strings using == operator. It's pointers comparasion.