I am using the following code and I am trying to check the command line arguments value. if the user entered the wrong values it will print an error message and exit the program. However, this approach did not work with me and I am new in c programming. Is there another way to achieve this?
int main(int argc, char *argv[])
{
int a;
int b;
int c;
if(argc != 4)
{
printf("Invalid usage of the file);
exit(0);
}
if ( ((atoi(argv[3])) != 1 || (atoi(argv[3]))) != 0 && (atoi(argv[1])) < 0 && (atoi(argv[2])) < 0 ) {
printf("Invalid arguments\n");
exit(0);
}
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
}
When I run the file, I am expecting that the user can only enter positive numbers for argv[1] and argv[2], and for argv[3] he can only enter 0 or 1. for example:
./filename 5 5 1
CodePudding user response:
Your code is overly complicated and the condition is wrong.
You want this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
if (argc != 4) // check argument count
{
fprintf(stderr, "Invalid usage of the file"); // rather print to stderr
exit(1); // use exit(1) in case of error
}
// retrieve arguments
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c = atoi(argv[3]);
// check validity of arguments
if (a < 0 || b < 0 || (c != 0 && c != 1)) {
fprintf(stderr, "Invalid arguments\n"); // rather print to stderr
exit(1); // use exit(1) in case of error
}
}
The parentheses around (c != 0 && c != 1)
are redundant, it's just for better redability.
(a < 0 || b < 0 || (c != 0 && c != 1)
in plain English:
a is smaller than 0 or b is smaller than zero or c is different from 0 and different from 1.