【问题标题】:RPN calculator in C programming using Linked Lists使用链表的 C 编程中的 RPN 计算器
【发布时间】:2016-01-22 06:36:41
【问题描述】:

我明天有一个任务,我刚刚开始。

我被要求使用链表做一个 RPN 计算器。

我的想法是我必须编写一个输入字符串,例如 (25 35 +),然后使用链表显示结果。

使用的结构是

typedef struct {
int data;
struct cell *next;}cell;

typedef struct {
int positif;
struct cell *datas;
int ref;} num ;

在上面的例子中,当我写 25 35 + 时,我必须将 25 作为一个数字存入堆栈,并且对 35 执行相同的操作,当读取操作符时,我执行操作呼叫 2 个 pop。

问题是我不知道如何在读取空格时将数字与字符串分开。

这是我的主线

 char strIn[250];
num *lenumero = initialisation(); 
printf(">");                      
scanf("%s", &strIn);               

int i=0;
while(strIn[i] != '\0')
{
    /*Here I want to write the code that reads the string untill it finds a space , 

然后它将空间前的数字压入堆栈!

}

例如 StrIn[0]=2 STrIn[1]=5 strIn[2]=(空格) 所以我将2放入一个cell->data,5放入cell->next->data,然后我将所有的cell放入结构编号使用的cell中,并将结构编号压入栈中。

谢谢

【问题讨论】:

  • 逆波兰表示法?
  • @erip,把反向波兰表示法称为 PRN 真是个绝妙的笑话!
  • 字符串( 25 35 + ) 不是有效的后缀表示法。后缀中没有括号。

标签: c stack calculator postfix-notation


【解决方案1】:

我假设这是一个 C 赋值,而不是 C++。

对于波兰符号,您不需要 paranthises。可能最简单的方法是使用strtok() 将输入字符串分解为空格分隔的标记,而不仅仅是检查标记是否等于“+”、“-”、“/”或“*”。如果不是,则将其读取为整数(例如,使用 sscanf)并将其作为数字推送。否则,作为操作推送。

【讨论】:

    【解决方案2】:

    正如 SergeyA 的回答中提到的,您可以使用带有空格的 strtok 作为分隔符。

    pointer = strtok(strIn, " ");
    while(pointer != NULL) {
      printf("%s\n", pointer); // this is where you put your logic to push the number to the stack.
      pointer = strtok(NULL, " ");
    }
    

    如果你想测试它是否是一个运算符(即“+-/*”中的任何一个),你可以使用strchr

    const char *operators = "+-/*";
    ...
    char *c = pointer;
    if(strchr(operators, *c)) {
      printf("%c is in \"%s\"\n", *c, operators); // replace this with your logic to read from the stack and calculate the numbers with the given operator.
    }else {
      while(*c) {
        printf("%c\n", *c); // this will print all the digits of the numbers
        c++;
      }
    }
    ...
    

    您的代码现在的问题是您正在使用scanf("%s", strIn);,它只会读取第一个字符串,直到空格。你应该做的是改用fgets

    fgets(strIn, 25, stdin);
    

    这是一个live 演示。

    【讨论】:

    • 好的,我知道了,现在有没有可能将输出中的 25 推入堆栈?例如 push(pointer[0],stack) .
    • @Zok 是的,您可以使用函数atoi 将字符串转换为整数并使用push(atoi(pointer), stack)。这将假设 push 接受一个整数作为参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 2014-05-04
    • 2013-10-18
    • 1970-01-01
    相关资源
    最近更新 更多