2 most important issues with you code:
- You SHALL check number of arguments BEFORE arguments check.
- Strings are compared using standard library functions like
strcmp()
or even better strncmp()
if you know maximum length.
Here is the C code that works. Hope this help.
#include <stdio.h>
#include <string.h>
int main (int argc, char* argv[])
{
if ((argc > 1) && ((strcmp(argv[1], "a") == 0)))
{
printf("hello world, argc: %d\n", argc);
}
else if ((argc > 1) && (strcmp(argv[1], "2") == 0))
{
printf("hello everyone, argc: %d\n", argc);
}
for (int i = 0; i < argc; i++)
printf("%s\n", argv[i]);
return 0;
}
Some details aout string comparison. If you use ==
operator here (if you have not overloaded it) you just compare object addresses (look carefully, you have char *
in both cases). Obviously your string literal and argument buffer have different addresses. You need to compare contents. Actually in C++ you can construct std::string
and use comparison operator.
So another, more C++ solution that works based on ==
operator:
#include <stdio.h>
#include <string>
int main (int argc, char* argv[])
{
if ((argc > 1) && (std::string(argv[1]) == "a"))
{
printf("hello world, argc: %d\n", argc);
}
else if ((argc > 1) && (std::string(argv[1]) == "2"))
{
printf("hello everyone, argc: %d\n", argc);
}
for (int i = 0; i < argc; i++)
printf("%s\n", argv[i]);
return 0;
}