I had just started learning programming in C language and I faced a simple problem, but I didn't know how to implement it

I want to write a program that accepts three arguments from the command line. Two arguments are
numbers while one argument is one of the operations. The main function
should read these arguments, if the number of arguments is not 3, then the program should
return the value -9999 and exit.

If the number of arguments is 3, then the program should perform
the operation between the two numbers and return the result of the operation.

I have written several lines but I know my code is not complete yet.
Could anyone help me to write the correct one? I want to check the number of arguments first then apply the operation.

#include <stdio.h>
 
void main(int argc, char * argv[])
{
    int a, b, result;
    char ch;
 
    printf("enter two numbers and the operation to apply on: \n");
    a = atoi(argv[1]);
    b = atoi(argv[2]);
    ch  = *argv[3];
    printf("%d %d %c", a, b, ch);
    switch (ch)
    {
    case '+':
        result = a + b;
        break;
    case '-':
        result = a - b;
        break;
    case 'x':
        result = a * b;
        break;
    case '/':
        result = a / b;
        break;
}
    printf("\nThe result of the operation is %d", result);
    printf("\n");    
}

>Solution :

if the number of arguments is not 3

Check argc before you try to access the arguments.

if (argc != 4) {
    /* Print usage message and exit */
}

if the number of arguments is not 3, then the program should return
the value -9999 and exit.

That’s an arbitrary requirement. Use EXIT_FAILURE and EXIT_SUCCESS instead cluttering the code with magic numbers.


atoi(argv[1]);

provides no means of error checking. Consider using strtol() instead.

Aside:

  • Division by zero would exhibit undefined behaviour.
    From C11 6.5.5 paragraph 5:

The result of the / operator is the quotient from the division of the
first operand by the second; the result of the % operator is the
remainder. In both operations, if the value of the second operand is
zero, the behavior is undefined.

  • You are missing a header file.
  • main() should be declared to return an int.
  • Those operations could result in an integer overflow/underflow.

Leave a Reply