Help with basic programming

2019-07-04 09:29发布

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.

2条回答
Fickle 薄情
2楼-- · 2019-07-04 09:49
*++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;
}
查看更多
萌系小妹纸
3楼-- · 2019-07-04 09:50

Instead of accessing the command line args via pointers, easily you can do this using array referencing. 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;
}
查看更多
登录 后发表回答