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

Boolean Calculator How to check user input using stacks c++

我正在制作一个计算器,用户可以在其中输入 <,>,<=,>=,&&,||, ==,!即 (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);
}





}

operations 是一个 stack<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> 并推送包含完整运算符(一个或两个字符)的字符串,而不是一个字符一个字符地推送。

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

中用双引号而不是单引号括住您的常量

重要提示

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