I have been trying to work with C++ console app on linux.
I want to change the options of the user depending on what parameter he used.
Like: ./my -n 1234 or ./my -f file.txt
-n or -f is always argv[1]
1234 or file.txt is always argv[2]
my main()
int main(int argc, char *argv[])
Here is my code so far:
string numlist, num;
if (argc < 3) {
fprintf(stderr,"usage stuff...%s %s", argv[0], argv[0]);
exit(0);
}
char *f = "-f";
char *n = "-n";
char *argv0 = argv[0];
char *argv1 = argv[1];
char *argv2 = argv[2];
if (strcmp(argv1, f) == 0){
numlist = argv[2];
//more data for this parameter
}
if (strcmp(argv1, n) == 0){
num = argv[2];
//more data for this parameter
}
Problem:
when i try ./my -n 1234
This should skip 1st if block, then execute 2nd if block.
or ./my -f file.txt
Should execute the 1st if block, and skip the 2nd if block.
Now with my current code if i enter either -n or -f it skips all if blocks.
— edit —
I guess I fixed it the problem was actually not on the argv but on my if blocks.
Thanks everyone I’ll check all your suggestions.
I don’t know what’s your complete source code but here is what it worked for me:
I’ve added the
using namespace stdto make the writing of the code easier, also i’ve moved the validation to the top, because if argv[2] doesn’t exists, it will throw an error.