Sir
Sir

Reputation: 8280

Loading values from a text file C++

I have a text file named settings.txt. Inside it i have it saying:

Name = Dave

I then open the file and loop the lines and characters in my script:


    std::ifstream file("Settings.txt");
    std::string line;

    while(std::getline(file, line))
{
    for(int i = 0; i < line.length(); i++){
        char ch = line[i];

        if(!isspace(ch)){ //skip white space

        }

    }
}

What I am trying to work out is assign each value to some kind of variable which will count as my "global settings" for the game.

So the end result would be something like :

Username = Dave;

But in such a way i can add extra settings at a later date. I can't work out how you would do it =/

Upvotes: 0

Views: 4983

Answers (1)

Baiyan Huang
Baiyan Huang

Reputation: 6771

To add extra setting, you have to reload the setting file. By keeping setting in a std::map, new settings can be added, or override existing setting. here is an example:

#include <string>
#include <fstream>
#include <iostream>

#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>

#include <map>

using namespace std;

/* -- from Evan Teran on SO: http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring -- */
// trim from start
static inline std::string &ltrim(std::string &s) {
        s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
        return s;
}

// trim from end
static inline std::string &rtrim(std::string &s) {
        s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
        return s;
}

// trim from both ends
static inline std::string &trim(std::string &s) {
        return ltrim(rtrim(s));
}

int main()
{
    ifstream file("settings.txt");
    string line;

    std::map<string, string> config;
    while(std::getline(file, line))
    {
        int pos = line.find('=');
        if(pos != string::npos)
        {
            string key = line.substr(0, pos);
            string value = line.substr(pos + 1);
            config[trim(key)] = trim(value);
        }
    }

   for(map<string, string>::iterator it = config.begin(); it != config.end(); it++)
   {
        cout << it->first << " : " << it->second << endl;
   }
}

Upvotes: 2

Related Questions