I would like a user to pass either two parameters or leave it blank. For instance:
./program 50 50
or
./program
When I tried to use int main(int argc, char *argv[])
, first thing I have done was to change char *argv[]
to int *argv[]
but it did not work. What I want is from the user is just to enter two integers between 0 and 100. So if it is not two integers then it should give an error.
I was sort of thinking to give out an error with types (as I used to program on C#) but whatever I enter, argv[1] would be 'char' type all the time.
So what I have done is
for (int i = 0; i <= 100; i++) {
//printf("%d", i);
if (argv[1] == i) {
argcheck++;
printf("1st one %d\n", i);
}
else if (argv[2] == i) {
argcheck++;
printf("2nd one %d\n", i);
}
This does not work as well. Also it gives warning when compiling, but if I change argv
with atoi(argv[1])
for instance, then it gives a Segmentation fault (core dumped) error.
I need a simple way to solve this problem.
EDIT:
So I fixed with atoi()
, the reason why it was giving segmentation fault was because I was trying it with null value when I have no parameter. So I fixed it up by adding an extra cond. But now the problem is if the value is let's say
./program asd asd
Then the output of atoi(argv[1])
would be 0. Is there a way to change this value?
Command line arguments are found in the argv array - argv[1], argv[2] etc. Converting a string argument to an integer can be done with the atoi function. Output can be done with the printf function.
Argument Parsing using sys. Your program will accept an arbitrary number of arguments passed from the command-line (or terminal) while getting executed. The program will print out the arguments that were passed and the total number of arguments. Notice that the first argument is always the name of the Python file.
Don't use atoi()
and don't use strtol()
. atoi()
has no error checking (as you found out!) and strtol()
has to be error-checked using the global errno
variable, which means you have to set errno
to 0, then call strtol()
, then check errno
again for errors. A better way is to use sscanf()
, which also lets you parse any primitive type from a string, not just an integer, and it lets you read fancy formats (like hex).
For example, to parse integer "1435" from a string:
if (sscanf (argv[1], "%i", &intvar) != 1) {
fprintf(stderr, "error - not an integer");
}
To parse a single character 'Z' from a string
if (sscanf (argv[1], "%c", &charvar)!=1) {
fprintf(stderr, "error - not a char");
}
To parse a float "3.1459" from a string
if (sscanf (argv[1], "%f", &floatvar)!=1) {
fprintf(stderr, "error - not a float");
}
To parse a large unsigned hexadecimal integer "0x332561" from a string
if (sscanf (argv[1], "%xu", &uintvar)!=1) {
fprintf(stderr, "error - not a hex integer");
}
If you need more error-handling than that, use a regex library.
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