I have this code:
if (argv[i] == "-n")
{
wait = atoi(argv[i + 1]);
}
else
{
printf("bad argument '%s'\n",argv[i]);
exit(0);
}
When this code gets executed I get the following error:
bad argument '-n'
I seriously don't know why it does that. Can someone explain?
String comparisons need a function in C - usually strcmp()
from <string.h>
.
if (strcmp(argv[i], "-n") == 0)
{
wait = atoi(argv[i + 1]);
}
else
{
printf("bad argument '%s'\n",argv[i]);
exit(0);
}
The strcmp()
function returns a negative value (not necessarily -1) if the first argument sorts before the second; a positive value (not necessarily +1) if the first arguments sorts after the second; and zero if the two values are equal.
The ==
operator does not work on the contents of strings because strings are effectively character pointers in this application, and the pointer get compared.
To compare the contents of strings use strcmp
or strncmp
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With