我已经尝试过使用atoi
然后将它们切换回字符串来推送,我正在尝试为类制作一个 rpn 计算器,因此推送、弹出、查找和堆栈结构是需要的,但我无法让它添加整数价值观。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct stack
{
const char * data;
struct stack *bottom;
};
struct stack * push(struct stack *stk,const char * x)
{
struct stack *nstk = (struct stack *)malloc(sizeof(struct stack));
nstk->data = x;
nstk->bottom = stk;
return nstk;
}
const char * peek(struct stack *stk)
{
if(stk -> data)
return stk->data;
else
return("Stack is empty");
}
struct stack *pop(struct stack *stk)
{
struct stack *tmp;
tmp = stk->bottom;
stk->bottom = NULL;
free(stk);
return tmp;
}
FILE * input_from_args(int argc,const char *argv[])
{
if(strcmp(argv[1],"-e") != 0 && strcmp(argv[1],"-c") != 0 && strcmp(argv[1],"-g") != 0)
{
printf("Option %s is not supported \n", argv[1]);
exit(0);
}
else
{
return stdin;
}
}
void evaluate(struct stack * equation)
{
int op;
int op2;
int ans;
if(strcmp("A",equation->data) == 0)
{
op = (int)pop(equation)-> data;
op2 = (int)pop(equation)-> data;
ans = op + op2;
printf("%i",ans);
}
}
void convert(struct stack * equation)
{
}
void other (struct stack * equation)
{
}
int main(int argc,const char *argv[])
{
FILE *src = input_from_args(argc, argv);
if (src == NULL)
{
printf("%s", "Invalid Source");
exit(EXIT_FAILURE);
}
struct stack * equation = NULL;
int i;
for(i=2; i <= argc; i++)
{
equation = push(equation,argv[i]);
}
if(strcmp(argv[1],"-e") == 0)
{
evaluate(equation);
}
else if(strcmp(argv[1],"-c") == 0)
{
convert(equation);
}
else if(strcmp(argv[1],"-g") == 0)
{
other(equation);
}
return EXIT_SUCCESS;
}
如果您发现任何其他问题都很好,这就是我到目前为止所拥有的一切,但我真正想知道的是如何使用此数据结构评估后缀方程输入示例为 -e 2 2 A 5 X。