Read Config File

The code below parses the config file. After we successfully load the file, we read it line by line. We remove all the white-spaces from the line and skip the line if it is empty or contains a comment (indicated by "#"). After that, we split the string "name=value" at the delimiter "=" and print the name and the value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <fstream>
#include <algorithm>

int main()
{
    // std::ifstream is RAII, i.e. no need to call close
    std::ifstream cFile ("config2.txt");
    if (cFile.is_open())
    {
        std::string line;
        while(getline(cFile, line))
       {
            line.erase(std::remove_if(line.begin(), line.end(), isspace),
                                 line.end());
            if( line.empty() || line[0] == '#' )
            {
                continue;
            }
            auto delimiterPos = line.find("=");
            auto name = line.substr(0, delimiterPos);
            auto value = line.substr(delimiterPos + 1);
            std::cout << name << " " << value << '\n';
        }
    }
    else 
    {
        std::cerr << "Couldn't open config file for reading.\n";
    }
}
So, what's your concern/problem?
It is probably what line 14 is doing to the key/value data.
There are some string utils here, check out the trim(): http://www.cplusplus.com/forum/beginner/230503/

You'll need an "std::" in front of getline on line 12.
The only problem I see is that it won't work if a non-comment line contains no '=' character.

Line 14 removes all spaces from the line, but that's what the OP said should happen.
Honestly, you are wasting your time not using SimpleIni
https://github.com/brofield/simpleini

All problems fixed.
Thanks All.
Topic archived. No new replies allowed.