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?
Don’t use
atoi()and don’t usestrtol().atoi()has no error checking (as you found out!) andstrtol()has to be error-checked using the globalerrnovariable, which means you have to seterrnoto 0, then callstrtol(), then checkerrnoagain for errors. A better way is to usesscanf(), 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:
To parse a single character ‘Z’ from a string
To parse a float “3.1459” from a string
To parse a large unsigned hexadecimal integer “0x332561” from a string
If you need more error-handling than that, use a regex library.