0

This is my code:

I have a problem with the evaluate function. I want to sscanf 2 characters from token[i] and determine weather its a +,-,*,/ or a number.

I used sscanf because I dont have any idea how to convert a string into double. If i include string.h it has to be working but it doesnt. It looked like its working but i am getting segmentation fault at onilne compilers. I dont know how to fix this problem. Thank you for your help.

Can you recommend a solution to convert string into double?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct listelem{
    double a;
    struct listelem *next;
}listelem;

void push(listelem *stack, double a)
{


    create linked list....

     
}

double pop(listelem *stack)
{


    pop linked lis...


}

double evaluate(char *token[], int n)
{
    listelem *list = (listelem*)malloc(sizeof(listelem));
    list->a = 100;
    list->next = NULL;
    double eredmeny = 0;
    double szam;
    char c[2];
    for(int i = 0; i < n; i++){
     strcpy(c, token[i]);
     if((c[0] == '+' || c[0] == '-' || c[0] == '*' || c[0] == '/') && !('0' <= c[1] && c[1] <= '9')){
            switch(c[0]){
                case '+':
                    push(list, pop(list) + pop(list));
                    break;

                case '-':
                    push(list, -(pop(list) - pop(list)));
                    break;

                case '*':
                    push(list, pop(list) * pop(list));
                    break;

                case '/':
                    push(list, 1/(pop(list) / pop(list)));
                    break;
            }
        }
        else{
            sscanf(token[i], "%lf", &szam);
            push(list, szam);
        }
    }
    eredmeny = list->next->a;
    free(list->next);
    free(list);
    return eredmeny;
}

int main(void)
{
    char *token[] = {"1.5", "2", "+"};

    printf("%f\n", evaluate(token, 3));


    return 0;
}
durgo
  • 3
  • 2
  • `token[i]` might be longer than 2 characters so you need to do [`strncpy(c, token[i], sizeof(c));`](http://www.cplusplus.com/reference/cstring/strncpy/). – dbc Dec 12 '20 at 15:35
  • Did that resolve your problem? If not we need to see a [mcve] -- code + data that fully reproduces the problem. See: [ask]. – dbc Dec 12 '20 at 19:29

0 Answers0