注册 登录
编程论坛 数据结构与算法

请教!

shujujiegou1 发布于 2012-10-14 12:17, 354 次点击
我想实现一个将中缀表达式转化为后缀表达式的程序,请问这是错在哪了??
#include "stdafx.h"
#include<stack>
#include<iostream>
#include<string>
using namespace std;

int main()
{
    stack<char> op;
    string s;
    cout<<"请输入表达式: ";
    cin>>s;
    istringstream in(s);
    char c;
    while(in>>c)
    {
        if(c=='+'||c=='-'||c=='*'||c=='/')
            op.push(c);
        else if(c==')')
        {
            cout<<op.top()<<" ";
            op.pop();
        }
        else if(c>='0'&&c<='9')
        {
            in.putback(c);
            int n;
            cin>>n;
            cout<<n<<" ";
        }
    }
    while(!op.empty())
    cout<<op.pop()<<endl;
    return 0;
}
1 回复
#2
爱闹的娃2012-10-14 21:33
大概的调试了一下程序,调出来一大堆错误.....首先你没有加头文件sstream
主要错误在于op.pop()(并没有返回值),
它的意思是删除栈顶元素,
你得用op.top()...它返回来的才是栈顶元素....修改后的代码:
程序代码:
#include<sstream>
#include<string>
#include<iterator>
using namespace std;
int main()
{
    stack<char> op;
    string s;
    cout<<"请输入表达式: ";
    cin>>s;
    istringstream in(s);
    char c;
    while(in>>c)
    {
        if(c=='+'||c=='-'||c=='*'||c=='/')
            op.push(c);
        else if(c==')')
        {
            cout<<op.top()<<" ";
            op.pop();
        }
        else if(c>='0'&&c<='9')
        {
            in.putback(c);
            int n;
            cin>>n;
            cout<<n<<" ";
        }
    }
      
     while(!op.empty())
     {
       cout<<op.top()<<endl;
       op.top();
      }
    return 0;
}


[ 本帖最后由 爱闹的娃 于 2012-10-14 21:59 编辑 ]
1