【发布时间】:2015-09-13 21:38:38
【问题描述】:
我正在做一个从后缀转换为中缀表达式的项目。我被困了一段时间,但我有一部分工作,然后我意识到当我将每个操作数输入给用户时我需要在每个操作数之间包含一个空格。我不知道如何接受一个字符串而不包含空格我将如何去做。 getline 不起作用,因为它包含空格。因此,我需要将其接受为:a b +,而不是 ab+。我不确定如何做到这一点,不包括字符串。到目前为止,这是我的代码。
#include "stack.h"
void convert(string expression){
stack c;
string post =" ";
string rightop="";
string leftop="";
string op ="";
for (int i =0; i<=expression.length()-1;i++){
c.push(expression[i]);
c.print();
if (expression[i] == '*' ||
expression[i] == '+' ||
expression[i] == '-' ||
expression[i] == '/'){
cout<<c.top()<<endl;
leftop=c.top();
cout<<leftop<<endl;
c.pop();
rightop=c.top();
cout<<rightop<<endl;
c.pop();
op=c.top();
cout<<op<<endl;
c.top()=expression[i+1];
//c.pop();
post="(" + leftop + " " + op + " " + rightop + ")";
cout<<post<<endl;
}
//c.push(post);
}
}
int main(){
string expression;
cout<<" Enter a Post Fix expression: ";
getline(cin,expression);
convert(expression);
return 0;
}
【问题讨论】:
标签: c++ string input stack getline