Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with basic programming

Tags:

c

command-line

This issue I feel is more my understanding of pointers but here goes. I am suppose to create a system program in C that performs calculations as such math operator value1 value2. Example math + 1 2. This would produce 3 on the screen. I am having troubles comparing or summing the numbers. Here is what I have so far:

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

int main( int ac, char* args[] )
{
    int total;
    if (strcmp(*++args,"+") == 0)
    {

    }
    printf("Total= ", value1);
    if (strcmp(*args,"x") == 0)
        printf("multiply");
    if (strcmp(*args,"%") == 0)
        printf("modulus");
    if (strcmp(*args,"/") == 0)
        printf("divide");
    return 0;
}

I can do a string compare to get the operator but am having a hard time adding the two values. I have tried:

int value1=atoi(*++args);

Any help would be appreciated.

like image 874
shayster01 Avatar asked Aug 01 '26 16:08

shayster01


1 Answers

*++args

Since you are doing a pre-increment ++ operator has higher precedence than * so the pointer is incremented and later you are dereferencing it which case you might never get to access the arguement which you actually intend to.

If you have input like

+ 1 2

We have

args[1] = +

args[2] = 1

args[3] = 2;

Why can't just access atoi(args[2])

You can do something like

int main(int argc, char **args)
{
    if(argc != 4)
    {
        printf("Fewer number of arguements\n");
        return 0;
    }

    else if((strcmp(args[1],"+")) == 0)
    {
      printf("Sum = %d\n",atoi(args[2]) + atoi(args[3]));
    }

    return 0;
}
like image 181
Gopi Avatar answered Aug 07 '26 08:08

Gopi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!