//Checks if a arguement 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?
Thanks in advance.
Use argc
for knowing how main arguments are passed. Shell or process invoker feeds the program with atleast one argument in general, that is program name itself and that is always the first argument. It turns out that argc=1
atleast, and argv[0]
is program name.
int main(int argc, char **argv){
// declarations and all here
if(argc<2){
strcpy(Buff1, "default");
}
else{
strcpy(Buff1, argv[1]);
}
return 0;
}
With out using this, you have two problems. When you use argv[1]
, when argc=1
, you are actually going array out of bounds. Since, c++
doesn't do any bounds check for you, sometimes your program might fail silently accessing memory address next to the argv[0]. And another problem is that you are trying to compare the strings with !=
operator. You can't compare string literals right away with ==
/!=
operator. You have to use strcmp
or an equivalent function.