我一直在一個項目上工作,我幾乎完成了我最後一個問題是創建一個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<<")";
}
}
我又試了一遍,它沒有回到第一個問題。我認爲這可能是我的轉換函數關閉它不確定。 –
當你按照你寫的程序運行程序時,你說它只運行一次循環。接下來發生什麼?程序是否終止或卡住了? 我想要得到的是你的convert()函數卡在無限循環或阻塞,或者你的convert()函數拋出一些導致程序終止的錯誤 – jose