【发布时间】:2015-09-14 01:26:06
【问题描述】:
我一直在做一个项目,我几乎完成了我遇到的最后一个问题,即创建一个 while 循环,不断询问用户是否要转换表达式。到目前为止,它只做了一次,然后就不再继续询问了。我知道这是一个简单的问题,我认为我的逻辑是错误的,但由于某种原因它不起作用。
这是我的主要内容:
int main(){
string answer=" ";
string expression;
while(answer!="no"){
cout<<"Would you like to do a conversion,type yes or no:";
getline(cin,answer);
cout<<" Enter a Post Fix expression:";
getline(cin,expression);
convert(expression);
}
return 0;
}
虽然对于我的问题来说并不是真正必要的,但我的主要代码上方的代码以防万一:
/*
* PLEASE DO NOT PLACE A SPACE BEFORE YOU INPUT THE FIRST OPERAND
*
*
*/
#include "stack.h"
void convert(string expression){
stack k; //Stores raw input string
stack c; //stores input string without spaces
stack s;//stores the string values
string post =" ";
string rightop="";
string leftop="";
string op ="";
int countop=0;// counts the number of operators
int countoper=0;// counts the number of operands
for (int i =0; i<=expression.length()-1;i++){
k.push(expression[i]);
if(expression[i] == '*' ||
expression[i] == '+' ||
expression[i] == '-' ||
expression[i] == '/')
{
countop++;
}
}
c.push(expression[0]);
int count=expression.length()/2;
countoper=(count-countop)+1;
if (countop==countoper){ //tells when there are too many opertors and not enough operands
cout<<"too many operators and not enough operand"<<endl;
exit(1);
}
if(countop==countoper*2){ //tells when there are too many opertors and not enough operands
cout<<"too many operands and not enough operators"<<endl;
exit(1);
}
for(int i=1;i<=expression.length()/2;i++){
c.push(expression[2*i]);
}
for(int i=0; i<2;i++){
leftop=c.top();
c.pop();
rightop=c.top();
c.pop();
op=c.top();
c.pop();
post="(" + leftop + " " + op + " " + rightop + ")";
s.push(post);
if(count<6){
cout<<s.top()<<endl;
}
}
if (count>=6){
cout<<"(";
cout<<s.top();
cout<<c.top();
s.pop();
cout<<s.top();
cout<<")";
}
}
【问题讨论】:
标签: loops menu while-loop stack main