Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking cmd line arguments in C

I am trying to take 2 parameters from the cmd line in C. The second number must not be higher than 100. However, when running the program with 23 405, it executes without any errors.

int main(int argc, char * argv[]){
    char *inputs;
    int input1= strtol(argv[1], &inputs, 10);
    int input2= strtol(argv[2], &inputs, 10);

   if ((*inputs!='\0') || (argc < 3) || (input1 > 1) || (input2 >= 100) 
   || (input1 >= input2))
   {
   printf("Error.");
   return 1}
  return 0;
}

I am new to C so any help is greatly appreciated!


2 Answers

  1. Before use argv[2] should make sure argc >= 3
  2. The line return 1} should be return 1;}

The following code could work:

#include<stdio.h>

int main(int argc, char * argv[]) {
    if (argc < 3) {
        perror("Error");
        return 1;
    } 

    char *inputs1;
    char *inputs2;

    int input1= strtol(argv[1], &inputs1, 10);
    int input2= strtol(argv[2], &inputs2, 10);

    if (*inputs1!='\0' || *inputs2 != '\0' || input1 > 1 || input2 >= 100 || input1 >= input2) {
        printf("Error.");
        return 1;
    }
    return 0;
}
like image 179
Yunbin Liu Avatar answered Aug 08 '26 09:08

Yunbin Liu


I'm not sure what the purpose of inputs is (unless checking for input errors as pointed out by @yano). Consider the following:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[])
{
    int input1, input2;

    /* Check For Error */
    if(argc != 3)
    {
        printf("Need Two!\n");
        return 2;
    }

    input1= strtol(argv[1], NULL, 10);
    input2= strtol(argv[2], NULL, 10);

    printf("input1: %d,  input2: %d\n", input1, input2);

    if ((input1 > 1) || (input2 >= 100) || (input1 >= input2))
    {
        if(input1 > 1)
            printf("input1 must be 1 or less!\n");
        if(input2 >= 100)
            printf("input2 must be 99 or less!\n");
        if(input1 >= input2)
            printf("input1 must be less than input2!\n");

        return 1;
    }

    return 0;
}

Are your requirements that:

  1. input1 must be less than 2
  2. input2 must be less than 100
  3. input1 must be less than input2

Output

$ gcc main.c -o main.exe; ./main.exe;
Need Two!

$ gcc main.c -o main.exe; ./main.exe -8 11;

$ gcc main.c -o main.exe; ./main.exe 13 11;
input1 must be 0 or less!
input1 must be less than input2!

$ gcc main.c -o main.exe; ./main.exe 0 100;
input2 must be 99 or less!

$ gcc main.c -o main.exe; ./main.exe -5 -10;
input1 must be less than input2!
like image 26
Fiddling Bits Avatar answered Aug 08 '26 08:08

Fiddling Bits