Programming/C++ & Unreal

C++ config parser

장형이 2019. 5. 26. 14:46

텍스트를 파싱하는 로직이 필요해서 간단히 작성한 프로그램.

긴 설명은 필요없을 것 같아 소스만 남김!

 

사용법

#include <iostream>
#include "ConfigParser.h"

int main()
{
	CConfigParser test("test.ini");
	if (test.IsSuccess()) {
		std::cout << test.GetInt("IntTest") << std::endl;
		std::cout << test.GetBool("BoolTest") << std::endl;
		std::cout << test.GetString("StringTest") << std::endl;
		std::cout << test.GetFloat("FloatTest") << std::endl;
	}
	return 0;
}

 

ConfigParser.h

#pragma once
/*
*		Config 파일을 파싱하는 클래스
*/

#include <string>
#include <map>

class CConfigParser {
public:
	CConfigParser(const std::string& path); 
	bool IsSuccess() { return m_table.size() != 0; }
	bool Contain(const std::string& name);
	bool GetBool(const std::string& name);
	std::string GetString(const std::string& name);
	float GetFloat(const std::string& name);
	int GetInt(const std::string& name);

private:
	std::map<std::string, std::string> m_table;
};

 

ConfigParser.cpp

#include "ConfigParser.h"
#include <fstream>
#include <iostream>
#include <stdexcept>

CConfigParser::CConfigParser(const std::string& path)
{
	// read File
	std::ifstream openFile(path);
	if (openFile.is_open()) {
		std::string line;
		while (getline(openFile, line)) {
			std::string delimiter = " = ";
			if (std::string::npos == line.find(delimiter)) delimiter = "=";
			std::string token1 = line.substr(0, line.find(delimiter)); // token is "scott"
			std::string token2 = line.substr(line.find(delimiter) + delimiter.length(), line.length()); // token is "scott"
			m_table[token1] = token2;
		}
		openFile.close();
	}
}

bool CConfigParser::Contain(const std::string& name)
{
	if (m_table.find(name) == m_table.end()) return false;
	return true;
}

bool CConfigParser::GetBool(const std::string& name)
{
	if (Contain(name)) {
		if (m_table[name][0] == 't' || m_table[name][0] == 'T') return true;
		else return false;
	}
	else {
		throw std::invalid_argument("Not exist Name.");
	}
}

std::string CConfigParser::GetString(const std::string& name)
{
	if (Contain(name)) {
		if (m_table[name].find("\"") == std::string::npos) return m_table[name];
		else return m_table[name].substr(1, m_table[name].length() - 2);
	}
	else {
		throw std::invalid_argument("Not exist Name.");
	}
}

float CConfigParser::GetFloat(const std::string& name)
{
	if (Contain(name)) {
		return std::stof(m_table[name]);
	}
	else {
		throw std::invalid_argument("Not exist Name.");
	}
}

int CConfigParser::GetInt(const std::string& name)
{
	if (Contain(name)) {
		return std::stoi(m_table[name]);
	}
	else {
		throw std::invalid_argument("Not exist Name.");
	}
}