帮助基本编程

时间:2015-01-11 03:53:22

标签: command-line c

这个问题我觉得更多是我对指针的理解,但是这里有。我想在C中创建一个系统程序,它以数学运算符value1 value2的形式执行计算。示例math + 1 2.这将在屏幕上产生3。我在比较或总结这些数字时遇到了麻烦。以下是我到目前为止的情况:

#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;
}

我可以进行字符串比较以获取运算符但是很难添加这两个值。我试过了:

int value1=atoi(*++args);

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

*++args

由于您正在进行预增量++运算符的优先级高于*所以指针会递增,之后您将取消引用它,在哪种情况下您可能永远无法访问您实际的争论打算。

如果你有像

这样的输入

+ 1 2

我们有

args[1] = +

args[2] = 1

args[3] = 2;

为什么不能访问atoi(args[2])

您可以执行类似

的操作
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 :(得分:1)

您可以使用数组引用轻松地通过指针访问命令行args。例如,"math + 1 2",args [0]为math,args [1]为+等。

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;
}
相关问题