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;
}