利用string实现配置文件

//字符串trim函数
string trim(const string& str) {
    string t = "    abd  cdi   783     ";    //示例字符串
    t.erase(0, t.find_first_not_of(" \t\n\r"));     // "abd cdi   783     "      erase(int i,int j)是擦除从i到j的所有字符(含i,j位)
    t.erase(t.find_last_not_of(" \t\n\r") + 1);   // "abd cdi   783"          erase(int n)是擦除第n位置以后(含第n位置)的所有字符
    return t;

注:find_first_not_of(" \t\n\r")返回第一个不是这些字符(空格、制表符、换行、回车)的字符的位置

find_last_not_of函数则是返回从右往左数第一个符合条件的字符

 

//字符串分割函数
vector<string> split(string str,string pattern){
    string::size_type pos;
    vector<std::string> result;
    str+=pattern;//扩展字符串以方便操作
    int size=str.size();

    for(int i=0; i<size; i++)    {
        pos=str.find(pattern,i);
        if(pos<size){
            std::string s=str.substr(i,pos-i);
            s=trim(s);
            result.push_back(s);
            i=pos+pattern.size()-1;
        }
    }
    return result;
}

 

//此处实现一个简单的配置文件读取操作,比定义宏编译速度快
bool LoadFromFile(const string &account_info_file){
    //打开文件
    ifstream fin;
    fin.open(account_info_file.c_str());
    if (!fin){
        printf("get account info failed \n\t may be the file %s not exist!\n",account_info_file.c_str());
        return false;
    }

    //按行遍历
    string line;
    while(getline(fin,line)){
        line = trim(line);
        //为空或首字符为"#",则忽略
        if (line.empty() || line[0] == '#' ){
            continue;
        }

        vector<string> key_value = split(line,"=");
        if (stricmp(key_value[0].c_str(),SELF_DEFINE_STRING_CONFIG) == 0){    //SELF_DEFINE_STRING_CONFIG是键值对的key,而self_define_string_config_是键值对的value
            string self_define_string_config_ = key_value[1];
        }

    //关闭文件
    fin.close();
    return true;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lightypants

我需要你的帮助..

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值