从文件中读取键值对并忽略#注释行

Reading key value pairs from a file and ignoring # comment lines

本文关键字:注释 文件 读取 键值对      更新时间:2023-10-16

我想从文件中读取键值对,同时忽略注释行。

想象一个文件:

key1=value1
#ignore me!

我想出了这个,

a) 它看起来很笨重而且

b) 如果'='没有被空格包围,它就不起作用。lineStream没有被正确分割,整行都被读入了"key"。

    std::ifstream infile(configFile);
    std::string line;
    std::map<std::string, std::string> properties;
    while (getline(infile, line)) {
        //todo: trim start of line
        if (line.length() > 0 && line[0] != '#') {
            std::istringstream lineStream(line);
            std::string key, value;
            char delim;
            if ((lineStream >> key >> delim >> value) && (delim == '=')) {
                properties[key] = value;
            }
        }
    }

此外,欢迎对我的代码风格发表评论:)

我最近不得不制作一些解释器,读取配置文件并存储其值,这就是我的做法,它忽略了以#开头的行:

   typedef std::map<std::string, std::string> ConfigInfo;
    ConfigInfo configValues;
    std::string line;
        while (std::getline(fileStream, line))
        {
            std::istringstream is_line(line);
            std::string key;
            if (std::getline(is_line, key, '='))
            {
                std::string value;
                if (key[0] == '#')
                    continue;
                if (std::getline(is_line, value))
                {
                    configValues[key] = value;
                }
            }
        }

CCD_ 1是文件的CCD_。

部分来自https://stackoverflow.com/a/6892829/1870760

看起来没那么糟糕。我只想使用字符串::find来查找等号,而不是生成lineStream。然后将子字符串从索引0移到等号位置并对其进行修剪。(不幸的是,您必须自己编写修剪例程或使用boost例程。)然后将子串移到等号后面并进行修剪。