Hello all, just trying to understand how to do this simple function. All I want to do with this little program is to make a cli argument "-c" and have the program assign the integer that comes after it to a variable. It obviously doesn't need the loop for such a simple function, but this is just a test program for me to learn how to do this for future programs that probably will need it.
So:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//new.cpp
#include <iostream>
#include <stdio>
usingnamespace std;
int main(int argc, char* argv[])
{
int c = 0;
for (int i = 1; i < argc; ++i)
if( argv[i] == "-c" ) scanf("%d", &c);
cout << c << endl << argc << endl; //argc just to be sure that there are indeed 3 arguments
}
//Another try, with atoi.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
usingnamespace std;
int main(int argc, char* argv[])
{
int c = 0;
for (int i = 1; i < argc; ++i)
if( argv[i] == "-c" ) c = atoi(argv[i+1]);
cout << c << endl << argc << endl;
return 0;
}
./new -c 128
0
3
when I added the cout to the loop it ran 3 times and there are indeed 3 arguments in argc so I think there's probably only a couple things it could be...
1. It isn't picking up the -c it's invoked with for some reason or another.
2. I have no idea how scanf or atoi are supposed to be used (I have a feeling this is it...)
I've tried making main nothing but:
cout << argv[1] << endl;
and the output shows the -c it's being called with so I just don't get why the loop isn't working.
So I'd just like to get some opinions on the best way to have integers as cli arguments and what I'm doing wrong please.
I tried it again with scanf() and it seemed that the scanf() function was causing the program to hang, so I tried with atoi again and got it working correctly now thanks to you.
scanf returns an int which is equal to the number of values read - you should always make use of that to test whether it worked as expected. I am not sure whether you knew that already.
Also, your code looks like C code in a C++ program, perhaps you could aim to do things the "C++ way". It took me awhile to get used to that, I am still learning more "C++ things".
Any way I hope this isn't annoyingly trivial, hopefully provided a little that is useful.