递归求布尔表达式

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
bool factor();
bool term();
bool term() {
    char c = cin.peek();
    bool result = 0;
    if (c == '!') {
        result = term();
        result=!result;
        cin.get();
    }
    result = factor();
    bool more = 1;
    while (more) {
        c = cin.peek();
        if (c == '&' || c == '|') {
            cin.get();
            bool value;
            value = factor();
            if (c == '&') result = result & value;
            else result |= value;
        }
        else more = 0;
    }
    return result;
}
bool factor() {
    char c = cin.peek();
    bool result=0;
    if (c == '(') {
        cin.get();
        result=term();
        cin.get();
    }
    else if (c == 'V' || c == 'F') {
        if (c == 'V') result = 1;
        else result = 0;
        cin.get();
    }
    return result;


}
int main() {
    cout << term() << endl;
    while (1);
    return 0;
}

为什么识别不了感叹号???,初学不太懂,求指点,我也不知道程序对不对,目前第一个遇到的问题就是感叹号,

阅读 2k
1 个回答

第十一行后面要加一个 cin.get() 来吃掉"!", peek 求符号但并不从队列里删掉.

  if (c == '!') {
        cin.get();//eat up "!" symbol 
        result = term();
...

当然代码还有别的逻辑问题 , 你找找看.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题