C++ 使用堆栈的后缀计算
我正在尝试从txt文件中读取后缀表达式并对其求值 输入是10 5*,输出应该是50,但它只读取10和5, 他看不懂运算符也没有ascii码,有什么帮助吗? 这是我的密码C++ 使用堆栈的后缀计算,c++,file,stack,postfix-notation,C++,File,Stack,Postfix Notation,我正在尝试从txt文件中读取后缀表达式并对其求值 输入是10 5*,输出应该是50,但它只读取10和5, 他看不懂运算符也没有ascii码,有什么帮助吗? 这是我的密码 #include <iostream> #include <iomanip> #include <fstream> #include<stdio.h> #include<ctype.h> #include<stdlib.h> using namespace
#include <iostream>
#include <iomanip>
#include <fstream>
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
using namespace std;
#define SIZE 40
int stack[SIZE];
int top=-1;
void push(int n)
{
if(top==SIZE-1)
{
printf("Stack is full\n");
return;
}
else
{
top=top+1;
stack[top]=n;
printf("Pushed element is %d\n",n);
system("pause");
}
}
int pop()
{
int n;
if(top==-1)
{
printf("Stack is empty\n");
system("pause");
return 0;
}
else
{
n=stack[top];
top=top-1;
return(n);
}
}
int main()
{
int str[50],ch;
int i=0;
int n,op1,op2;
ifstream inFile;
ch=str[i];
inFile.open("D:\\me.txt");
if (!inFile)
{
printf( "Unable to open file");
system("pause");
exit(1); // terminate with error
}
while (inFile >> ch)
{
if(ch=='+' || ch=='-' || ch=='*' || ch=='/' || ch=='%' || ch=='^' )
{
op1=pop();
op2=pop();
if (op1<op2)
{
n=op1;
op1=op2;
op2=n;
}
if(ch=='+')
n=op1+op2;
else if(ch=='-')
n=op1-op2;
else if(ch=='*')
n=op1*op2;
else if(ch=='/')
n=op1/op2;
else if(ch=='%')
n=op1%op2;
else if(ch=='^')
n=op1^op2;
else
{
printf("The operator is not identified\n");
system("pause");
exit(0);
}
printf("n=%d\n",n);
system("pause");
push(n);
}
else
{
n=ch;
push(n);
}
ch=str[++i];
}
inFile.close();
printf("The value of the arithmetic expression is=%d\n",pop());
system("pause");
return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
#定义尺寸40
int堆栈[大小];
int top=-1;
无效推送(整数n)
{
如果(顶部==尺寸-1)
{
printf(“堆栈已满\n”);
返回;
}
其他的
{
顶部=顶部+1;
堆栈[top]=n;
printf(“推送的元素是%d\n”,n);
系统(“暂停”);
}
}
int-pop()
{
int n;
如果(顶部==-1)
{
printf(“堆栈为空\n”);
系统(“暂停”);
返回0;
}
其他的
{
n=堆栈[顶部];
top=top-1;
返回(n);
}
}
int main()
{
int-str[50],ch;
int i=0;
int n,op1,op2;
河流充填;
ch=str[i];
infle.open(“D:\\me.txt”);
如果(!infle)
{
printf(“无法打开文件”);
系统(“暂停”);
退出(1);//终止时出错
}
while(infle>>ch)
{
如果(ch='+'| | ch='-'| | ch='*'| | ch='/'| | ch='%'| | ch='^')
{
op1=pop();
op2=pop();
如果(op1问题是ch
是int
所以infle>>ch
将只读取numbers-忽略'*'
字符
此外,您还有一个未初始化的str[]
数组,您可以定期读取该数组以分配给ch
(然后忽略刚刚写入ch
)的内容。您需要去掉str[]
或者完成你最初把它放在那里的想法…问题是ch
是一个int
所以infle>>ch
将只读取numbers-忽略'*.
字符
此外,您还有一个未初始化的str[]
数组,您可以定期读取该数组以分配给ch
(然后忽略刚刚写入ch
)的内容。您需要摆脱str[]
,或者首先完成将其放在那里的想法