Creating a simple configuration file and parser in C++

前端 未结 12 745
谎友^
谎友^ 2020-12-07 10:55

I am trying to create a simple configuration file that looks like this

url = http://mysite.com
file = main.exe
true = 0

when the program ru

12条回答
  •  我在风中等你
    2020-12-07 11:37

    A naive approach could look like this:

    #include 
    #include 
    #include 
    #include 
    
    std::map options; // global?
    
    void parse(std::istream & cfgfile)
    {
        for (std::string line; std::getline(cfgfile, line); )
        {
            std::istringstream iss(line);
            std::string id, eq, val;
    
            bool error = false;
    
            if (!(iss >> id))
            {
                error = true;
            }
            else if (id[0] == '#')
            {
                continue;
            }
            else if (!(iss >> eq >> val >> std::ws) || eq != "=" || iss.get() != EOF)
            {
                error = true;
            }
    
            if (error)
            {
                // do something appropriate: throw, skip, warn, etc.
            }
            else
            {
                options[id] = val;
            }
        }
    }
    

    Now you can access each option value from the global options map anywhere in your program. If you want castability, you could make the mapped type a boost::variant.

提交回复
热议问题