布尔计算器如何使用堆栈c ++检查用户输入

时间:2015-10-22 21:21:34

标签: c++ stack boolean calculator

我正在制作一个计算器,其中用户输入可以输入<,>,< =,> =,&&,||, == ,!即,(2> 3)或(2> 3)&&(5< 3)等,并将其计算为真或假。问题是如何使用诸如"< =,> ="之类的表达式。使用if else语句。唯一有效的操作是"<"和">"。 这是检查输入是否与操作匹配的函数

  void evalute_stack_tops(std::stack<double>& numbers, std::stack<char>& operations){

      double operand1,operand2;


      operand2= numbers.top();
      numbers.pop();
      operand1= numbers.top();
      numbers.pop();


if(operations.top()=='<')
 {

    numbers.push(operand1<operand2);

 }
else if (operations.top()=='>')
 {

    numbers.push(operand1>operand2);


 }

else if(operations.top()=='>='){

    numbers.push(operand1 >= operand2);
}





}

1 个答案:

答案 0 :(得分:0)

operationsstack<char>,即一堆字符。因此,您一次只能访问一个字符。

如何解决?备选方案1:

您需要延长if阻止内容以检查'>''<'是否随后'='

示例:

...
if(operations.top()=='<') {
    operations.pop(); 
    if (operations.top()=='=') {
        numbers.push(operand1<=operand2);
        operations.pop(); 
    }
    else numbers.push(operand1<operand2); // and let top of op stack unchanged
 }

我不知道你是如何推动这些行动的。我假设">="会按相反顺序推送,因此首先是'=',然后是'>'。如果你反过来这样做,你必须适应。

如何解决?备选方案2

或者你可以考虑使operations成为std::stack<std::string>并推送包含完整运算符的字符串(一个或两个字符)而不是char字符。

这可能更容易:你不应该忘记在 if-expression

中的常量中放置双引号而不是单引号

重要提示

请注意,单引号仅包含一个字符。一旦你有多个单个字符,你应该考虑使用双引号来表明你的意思是字符串文字。并使用std :: string而不是char。