计算字符串的结果
#include<iostream>
#include<stack>
#include<string>
#include<sstream>
#include<vector>
#include<stdlib.h>
using namespace std;
int main(){
//一个字符一个字符的怎么处理
string s;
while(getline(cin,s)){
cout<<"s:"<<s<<endl;
if(s=="0") return 0;
stack<float> res;
vector<string> op;
vector<float> num;
istringstream is(s);
string temp;
while(is>>temp){
cout<<"temp:"<<temp<<endl;
if(temp=="+"||temp=="-"||temp=="*"||temp=="/"){
op.push_back(temp);
}
else{
num.push_back(atof(temp.c_str()));
}
}
if(op.size()==0){
printf("%.2f\n",num[0]);
continue;
}
for(int i=0,j=0;i<op.size()&&j<num.size();){
if(res.empty()){
res.push(num[j]);
++j;
}
if(op[i]=="+"){
res.push(num[j]);
++j;
++i;
}
else if(op[i]=="-"){
res.push(-num[j]);
++j;
++i;
}
else if(op[i]=="*"){
float temp=res.top();
res.pop();
res.push(temp*num[j]);
++j;
++i;
}
else{
float temp=res.top();
res.pop();
res.push(temp/num[j]);
++j;
++i;
}
}
//!!!作用域的问题
//!!!特别注意!!!对所有的变量都要初始化!!!!
//很神奇啊,这里必须要初始化,如果这里不初始化为0的话,每一次的ans就会累加
float ans=0;
while(!res.empty()){
cout<<"top:"<<res.top()<<endl;
ans+=res.top();
res.pop();
}
printf("%.2f\n",ans);
}
}
这里要注意学习的几个知识点为
1.如何输入带空格的一行字符串
2.如何将字符串按照空格分开
3.如何将字符串转化为int,float,double