使用链接列表的C编程中的RPN计算器

问题描述 投票:0回答:2

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

我被要求用链表做一个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声。

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

这是我的主要

 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中,然后将所有单元格放入该结构编号所使用的单元中,并将该结构编号压入堆栈中。

谢谢

c stack calculator postfix-notation
2个回答
0
投票

正如在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演示。


1
投票

我将假定它是C分配,而不是C ++。

对于波兰符号,您不需要寄生。可能最简单的方法是使用strtok()将输入字符串分成以空格分隔的标记,而不仅仅是检查标记是否等于'+''-'/'或'*'。如果不是,则将其读取为整数(例如,使用sscanf),然后将其作为数字推送。否则,请按一下操作。

© www.soinside.com 2019 - 2024. All rights reserved.