arrays - 为什么这个使用数组堆栈的 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
解决方案
scanf("%s",exp1);
遇到空白字符时将停止阅读。你应该fgets()
改用。
另外,不要忘记为读取表达式分配缓冲区。
char exp1[102400]; // believing that huge expression won't come
fgets(exp1, sizeof(exp1), stdin);
另请注意
printf(" , %d , ",strlen(exp1));
将为类型不匹配调用未定义的行为%d
:期望int
whilestrlen()
返回size_t
。要打印的格式类型说明符size_t
是%zu
. 如果您的环境不支持%zu
,则应在将返回值传递给int
之前将其转换为%d
。
推荐阅读
- android-emulator - Android Automotive Emulator“没有为此目标安装系统映像”
- python - 在 python 游标中读取一列打印很奇怪?
- javascript - 如何确定请求者是我的 Web 应用程序
- javascript - 如何在页面刷新时将用户的位置存储在相同的滚动位置
- node.js - 路由在 src/index.html 角度不起作用
- asp.net-core - Shieldui - ASP.Net Core CRUD 操作 - 弹出编辑
- regex - Notepad++ 书签行包含特定字符并使用正则表达式从字符串中间开始
- android - 为什么gradlew assembleDebug不运行jetifier,而react-native run-android运行jetifier?
- jquery - 如何删除 jQuery 数据表中的隐藏复选框
- python - 在Python中检查目录是否为空的最快方法是什么