Search code examples
cstackcalculatorpostfix-notation

RPN calculator in C programming using Linked Lists


I have an assignment due to tomorrow and I have just started it.

I was asked to do an RPN calculator using linked lists.

The idea is I have to write an input string , like ( 25 35 + ) , and display the result using linked lists.

the structure used are

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

and

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

in the example above , when I write 25 35 + , I have to stock the 25 as a number and push it into the stack , and do the same with the 35 , and when the operator is read , I do the operation calling 2 pops.

the problem is I do not know how to separate the numbers from the string when it reads a space.

this is my main

 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 , 

then it push the number before the space into the stack !

}

For example StrIn[0]=2 STrIn[1]=5 strIn[2]=(space) So I will put 2 into a cell->data , 5 into the cell->next->data , and then I put all the cell into the cell used in the structure number, and push the structure number into the stack .

Thank you


Solution

  • As mentioned in SergeyA's answer you can use strtok with a whitespace as delimter.

    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, " ");
    }
    

    If you want to test if it's an operator (i.e any of "+-/*") you can use 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++;
      }
    }
    ...
    

    The problem with your code right now is that you're using scanf("%s", strIn); which will only read the first string until the space. What you should do is use fgets instead.

    fgets(strIn, 25, stdin);
    

    Here is a live demo.