Basic programming help

This problem I feel is more my understanding of pointers, but here. I am supposing to create a system program in C that does the calculations as such the math operator value1 value2. Example math + 1 2. This will create 3 on the screen. I am having trouble comparing or summing numbers. Here's 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 comparison to get an operator, but I am having a hard time adding two values. I tried:

int value1=atoi(*++args);

      

Any help would be appreciated.

+3


source to share


2 answers


*++args

      

Since you are doing a pre-increment ++

, the operator has a higher precedence than *

, so the pointer is incremented and then you play it out, in which case you may never get access to the argument you are actually going to use.

If you have an input like

+ 1 2

We have



args[1] = +

args[2] = 1

args[3] = 2;

      

Why can't I 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;
}

      

+1


source


Instead of accessing the args command line through pointers, you can do so with an array reference. For example, "math + 1 2"

args [0] is math

, args [1] will be +

, etc.



int main( int ac, char* args[] )
{
    if(ac < 4)
    {
        printf("Invalid Argument");
        return 0;
    }
    if (strcmp(args[1],"+") == 0)
    {
        int x = atoi(args[2]);
        int y = atoi(args[3]);
        printf("%d + %d = %d\n", x,y, x + y);
    }
    if (strcmp(args[1],"x") == 0)
    {
        int x = atoi(args[2]);
        int y = atoi(args[3]);
        printf("%d * %d = %d\n", x,y, x * y);
    }
    if (strcmp(args[1],"%") == 0)
    {
        int x = atoi(args[2]);
        int y = atoi(args[3]);
        if(y == 0)
            return 0;

        printf("%d %% %d = %d\n", x,y, x % y);
    }
    if (strcmp(args[1],"/") == 0)
    {
        int x = atoi(args[2]);
        int y = atoi(args[3]);

        if(y == 0)
            return 0;
        printf("%d / %d = %d\n", x,y, x / y);
    }
    return 0;
}

      

+1


source







All Articles