3

I would like to read key value pairs from a file, while ignoring comment lines.

imagine a file like:

key1=value1
#ignore me!

I came up with this,

a) it seems very clunky and

b) it doesn't work if the '=' isn't surrounded by spaces. The lineStream isn't being properly split and the entire line is being read into "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;
            }
        }
    }

Also, comments on my code style are welcome :)

adapt-dev
  • 1,608
  • 1
  • 19
  • 30

2 Answers2

11

I had to make some interpreter that read in a configuration file and stored it's values recently, this is the way I did it, it ignores lines starting with # :

   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;
                }
            }
        }

fileStream being being an fstream of a file.

Partly from https://stackoverflow.com/a/6892829/1870760

Community
  • 1
  • 1
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

Doesn't look that bad. I just would use string::find to find the equal sign, instead of generating the lineStream. Then take the substring from index zero to the equal-sign position and trim it. (Unfortunately, you have to write the trim routine yourself or use the boost one.) Then take the substring behind the equal sign and also trim it.

nv3
  • 400
  • 4
  • 9