您的位置:首页 > 编程语言 > C语言/C++

逆波兰算法 C++——String及Stack实现

2018-01-22 21:29 148 查看
#include "cstdio"
#include "iostream"
#include "stack"
#include "string"
#include "sstream"

using namespace std;
stack<float> n;
stack<string> f;
int main(){
string s,buf;
float a,b;
float temp;
while(getline(cin,s)){
stringstream ss(s);
while(ss >> buf){
//  cout << buf;
if(buf[0] == '+'){
b = n.top();
//              cout << b <<endl;
n.pop();
a = n.top();
//              cout << a <<endl;
n.pop();
n.push(a+b);
//              cout << n.top()<<endl;
}
else if(buf[0] == '-'){
b = n.top();
n.pop();
a = n.top();
n.pop();
n.push(a-b);
}
else if(buf[0] == '*'){
b = n.top();
n.pop();
a = n.top();
n.pop();
n.push(a*b);
}
else {
stringstream toFloat;
toFloat << buf;
toFloat >> temp;
//              cout << temp <<endl;
n.push(temp);
}

}
cout <<n.top() << endl;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: