首页 > 解决方案 > 为什么这个使用数组堆栈的 c 中后缀输入计算器不起作用?

问题描述

我正在学习数据结构,当我经历时,我需要在 c 中制作一个后缀输入计算器我想使用堆栈和数组堆栈来制作它。我写了一些代码,但它没有给出输出而是给出了我输入的第一个单词它。如果我不接受输入并在字符串声明中给出值,这是可行的,但如果我要求输入,那么它不起作用。我还尝试在 scanf 之后打印 strlength,即使我的输入是 17 长度它也只打印 1。扫描 f 无法正常工作或 strlen 无法正常工作。我的代码是:-

#include <stdio.h>
#include <string.h>
#include "stack_forpostfix.h"

int postfix(char *exp);
int isoperator1(char b);
int isnumericdigit1(char c);
int doevaluation(int oper1,char optr,int oper2);

int main(){
    char *exp1;
    int a;
    printf("Enter the postfix expresssion\n");/*if we dont ask and put input in declaration the code works perfect,because if we ask the strlen is not working*/
    scanf("%s",exp1);       //2 3 * 5 4 * + 9 -
    printf(" , %d , ",strlen(exp1));
    a=postfix(exp1);
    printf("%d\n",a);
}

int postfix(char *exp){
   
    for(int i=0;i<strlen(exp);i++){
        if(exp[i]==' ' || exp[i]==','){
            continue;
        }
        else if(isoperator1(exp[i])){
            int op2=gettop();
            pop();
            int op1=gettop();
            pop();
            int result=doevaluation(op1,exp[i],op2);
            push(result);
        }

        else if(isnumericdigit1(exp[i])){
            int oper=0;

            while(i<strlen(exp) && isnumericdigit1(exp[i])){
                oper=(oper*10)+(exp[i]-'0');
                i++;
            }  //since i++ is there if no i-- exp[i] will escape one further
            i--;
            push(oper); 
        }
    }
    return gettop();    
}

int isnumericdigit1(char c){
    if (c>='0' && c<='9'){
        return 1;
    }
    else return 0;
}

int isoperator1(char b){
    if(b=='+'||b=='-'||b=='*'||b=='/'){
        return 1;
    }
    else {
        return 0;
    }
}

int doevaluation(int oper1,char optr,int oper2){

    if(optr=='+'){
        return oper1+oper2;
    }else if (optr=='-'){
        return oper1-oper2;
    }else if (optr=='*'){
        return oper1*oper2;
    }else if (optr=='/'){
        return oper1/oper2;
    }else {
        printf("not valid");
        return -1;
    }
}

我的头文件(stack_forpostfix.h)代码是:-

#ifndef stackyfix
#define stackyfix

#define maxsize 111


int a[maxsize];
int top=-1;

void push(int r){
    top++;
    a[top]=r;
}

void pop(){
    top--;
}

int gettop(){
    return a[top];
}
#endif

标签: arrayscstackpostfix-notation

解决方案


scanf("%s",exp1);

遇到空白字符时将停止阅读。你应该fgets()改用。

另外,不要忘记为读取表达式分配缓冲区。

char exp1[102400]; // believing that huge expression won't come
fgets(exp1, sizeof(exp1), stdin);

另请注意

printf(" , %d , ",strlen(exp1));

将为类型不匹配调用未定义的行为%d:期望intwhilestrlen()返回size_t。要打印的格式类型说明符size_t%zu. 如果您的环境不支持%zu,则应在将返回值传递给int之前将其转换为%d


推荐阅读