算法基础第三周001 Boolean Expressions

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
string str;
int in;//读
//循环定义,先申明
bool term();
bool expression();
bool factor();
bool expression(){
    //表达式
    bool result = term();
    bool more =true;//假设还有新的项
    while(more){
        if(str[in] == '|'){
            in++;//从输入取走字符
            bool value = term();//大问题递归分解成小问题
            result |= value;//或运算
        }
        else if(str[in] == ' '){
            in++;
            continue;
        }
        else if(str[in] == '\n'){
            in++;
            return result;
        }
        else more = false;//走完了
    }
    return result;
}
bool term(){
    //项
    bool result = factor();
    bool more =true;//假设还有新的因子
    while(more){
        if(str[in] == '&'){
            in++;
            bool value = factor();//大问题递归分解成小问题
            result &= value;//与
        }
        else if(str[in] == ' '){
            in++;
            continue;
        }
        else break;//项录入完了
    }
    return result;
}
bool factor(){
    //因子
    bool result;
    bool more = true;
    while(more){

        if(str[in] == '!'){
            in++;
            result = !factor();
        }
        else if(str[in]=='('){
            in++;
            result = expression();
            in++;//取走右括号
        }
        else if(str[in]==' '){
            in++;
            continue;
        }
        else{
            if(str[in]=='V'){
                in++;
                result = 1;
            }
            else if(str[in]=='F'){
                in++;
                result = 0;
            }
        }

        return result;
    }
}
int main(){
    int i = 1;
    in = 0;
    //freopen("in.txt","r",stdin);
    while(getline(cin,str)){//强制类型转换运算符的重载(把istream转换)
    in = 0;
    bool result = expression();
    cout<<"Expression "<<i<<": ";
    if(result)cout<<"V\n";
    else cout<<"F\n";
    i++;
    }
    getchar();
    return 0;
}

主要参考老师上课时的代码

  • 对一个不固定长度的行来说,换行符就是终止;而对于不固定长度的文件来说,EOF就是终止,getline遇到EOF会停止提取,并且返回一个istream对象
  • 之所以返回值istream在while中会进行真假判断,是因为C++进行了强制类型转换运算符的重载。

另外,学会了使用freopen,对流对象的理解加深了一点

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值