【问题标题】:If user inputs "sum(x,y)" how can I get x and y as doubles如果用户输入“sum(x,y)”我怎样才能得到 x 和 y 作为双打
【发布时间】:2021-06-01 14:40:08
【问题描述】:

我正在编写一个简单的计算器程序,以便用户进入程序自己的控制台环境。每个新行都以 $ 开头。用户将输入诸如 '''sum(x,y)''' '''mul(x,y)''' 等命令,程序将 x 和 y 作为双精度并执行一个函数,即 ''' double mul(x, y){return x*y)''' 并显示返回值。

我已经让它根据匹配字符串中的前三个字符正确识别命令。

无论我做什么,我似乎都无法正确读取数值。任何建议都非常感谢!

下面的代码来自 main()

    printf("%s", " $    ");
    fgets(input, sizeof(input), stdin);
    sscanf(input,"(%d,%d)",&arg1,&arg2);

    if(strstr(input,"sum")){
        //char *starting_pos = strchr(input,dlm);
        //int position = (starting_pos == NULL ? -1 : (uintptr_t)starting_pos);

        //arg1 = input[position + 1];
        //arg2 = input[position + 3];
        printf("DEBUG: arg1 is %d arg2 is %d\n", arg1,arg2);
        double output = sum(arg1,arg2);
        printf("DEBUG: Output should be: %d\n", output);
        printf("%d\n",output);

    }else if ...

评论部分是我尝试的另一种方式的残余。如果有人能告诉我这样做的正确方法是什么,我将不胜感激。

【问题讨论】:

  • arg1arg2 应该被声明为double,并且%lf 应该被用在sscanf 中,而不是%dsscanf 的返回值也应该检查过。
  • 如果你想要double 值,那么为什么sscanf(input,"(%d,%d)",&arg1,&arg2);arg1arg2 解析为int?为什么不char op[32]; ... if (sscanf(input,"%31[^(](%lf,%lf)", op, &arg1, &arg2) == 3) { /* valid op and args */ }

标签: c linux string input terminal


【解决方案1】:

很好地使用fgets() 阅读,然后使用sscanf() 解析值。如果我理解这个问题,并且您可能有多个运算符,后跟两个双精度括号,例如SUM(1.1, 2.2),如果你想将操作符和双精度值分开保存,则可以使用格式字符串如:

#define MAXOP   32
...
    char op[MAXOP];
    ...
    sscanf (input, "%31[^( ] (%lf,%lf)", op, &x, &y)

这将从input 读取,将所有内容分隔到一个空格或'('op,然后将双精度值读取到xy。通过将op 读取到空格或'(',您可以无缝输入sum(1.1, 2.2)sum (1.1, 2.2)

例如,你可以这样做:

#include <stdio.h>

#define MAXC  1024
#define MAXOP   32

int main (void) {
    
    while (1) {
        char input[MAXC], op[MAXOP];
        double x, y;
        
        fputs ("\nenter OP(x, y): ", stdout);
        fflush (stdout);
        
        if (!fgets (input, MAXC, stdin)) {
            puts ("(user canceled input)");
            return 0;
        }
        if (*input == '\n')
            break;
        
        if (sscanf (input, "%31[^( ] (%lf,%lf)", op, &x, &y) == 3)
            printf (" op: '%s'  x: %.2f  y: %.2f\n", op, x, y);
        else
            fputs ("  error: invalid input.\n", stderr);
    }
}

使用/输出示例

./bin/sumxy

enter OP(x, y): mult(10.1,12.4)
 op: 'mult'  x: 10.10  y: 12.40

enter OP(x, y): mult (8.3, 12.1)
 op: 'mult'  x: 8.30  y: 12.10

enter OP(x, y): sum(1.1, pickles)
  error: invalid input.

enter OP(x, y): sum(1.1, 2.2)
 op: 'sum'  x: 1.10  y: 2.20

enter OP(x, y):

如果您还有其他问题,或者我误解了问题,请告诉我。

【讨论】:

  • 这正是我想做的,非常感谢
  • 不客气。祝你编码好运!
猜你喜欢
  • 1970-01-01
  • 2022-01-13
  • 2012-11-25
  • 2015-07-02
  • 2019-05-13
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多