args.h 2.19 KB
Newer Older
1 2 3 4 5 6 7
#pragma once

#include <string>
#include <map>
#include <cstdlib>
#include <iostream>

Laurent Belcour's avatar
Laurent Belcour committed
8 9
#include "common.h"

10 11 12 13 14
class arguments
{
	public: // functions

		// Constructor and destructor
Laurent Belcour's avatar
Laurent Belcour committed
15 16 17
		arguments()
		{
		} ;
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
		arguments(int argc, char** const argv)
		{
			std::string key ;
			std::string data ;
			for(int i=0; i<argc; ++i)
			{
				std::string temp(argv[i]) ;
				std::string data ;

				if(temp.compare(0, 2, "--") == 0)
				{
					key = temp.substr(2, temp.size()-2) ;
					if(i+1 < argc) 
					{
						std::string next(argv[i+1]) ;
						if(next.compare(0, 2, "--") != 0)
						{
							data = next ;
						}
					}
				}
				_map.insert(std::pair<std::string, std::string>(key, data)) ;
			}
		} ;
		~arguments() { } ;

		// Access elements
		bool is_defined(const std::string& key) const
		{
			if(_map.count(key) > 0)
			{
				return true ;
			}
			else
			{
				return false ;
			}
		} ;
		std::string operator[](const std::string& key) const
		{
			if(_map.count(key) > 0)
			{
				return _map.find(key)->second ;
			}
			else
			{
				std::cerr << "Underfined request to key : \"" << key << "\"" << std::endl ;
				return std::string() ;
			}
		} ;
68
		float get_float(const std::string& key, float default_value = 0.0f) const
69
		{
70 71
			if(_map.count(key) > 0)
				return atof(_map.at(key).c_str()) ;
72
			else
73
				return default_value ;
Laurent Belcour's avatar
Laurent Belcour committed
74
		}
75
		int get_int(const std::string& key, int default_value = 0) const
76
		{
77 78
			if(_map.count(key) > 0)
				return atoi(_map.at(key).c_str()) ;
79
			else
80
				return default_value ;
Laurent Belcour's avatar
Laurent Belcour committed
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
		} 
		vec get_vec(const std::string& key, float default_value) const
		{
			vec res;
			if(_map.count(key) > 0)
			{
				std::string s = _map.at(key);
				if(s[0] == '\[') // Is an array of type [a, b, c]
				{
					int i = 0;
					size_t pos = 0;
					while(pos != std::string::npos)
					{
						size_t ppos = s.find(",", pos);

						if(ppos != std::string::npos)
						{
							std::cout << s.substr(pos, ppos) << std::endl ;
							res[i] = atof(s.substr(pos, ppos).c_str());
							pos = ppos+1;
							++i;
						}
					}
					return res;
				}
			}

			float val = get_float(key, default_value);
			res.push_back(default_value);
			return res;
		}
112 113 114 115 116 117

	private: // data

		std::map<std::string, std::string> _map ;

} ;