Yet another possibility:
Code:
#include <map>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
struct properties
{
void put( string const& name, string const& value = string( ) )
{
data[ name ] = value;
}
template < typename Type >
bool get( string const& name, Type* value )
{
if( data.find( name ) == data.end( ) )
return false;
stringstream
stream;
stream << data[ name ];
if( !( stream >> *value ) )
return false;
return true;
}
bool extract( string const& text )
{
stringstream
stream;
stream << text;
string
name;
getline( stream, name, '=' );
if( name.empty( ) )
return false;
string
value;
getline( stream, value );
if( value.empty( ) )
return false;
put( name, value );
return true;
}
map< string, string >
data;
};
int main( int argc, char** argv )
{
char const*
names[ ] =
{
"output-file-name",
"sub-period",
"factor"
};
properties
settings;
for( int index = 0; index < sizeof( names ) / sizeof( names[ 0 ] ); ++index )
settings.put( names[ index ] );
while( *( ++argv ) )
{
string
command = *argv;
if( settings.extract( command ) )
continue;
if( command.find( "=" ) != string::npos )
{
cerr << "Error: malformed setting string '" << command << "'" << endl;
continue;
}
cout << "Command: " << command << endl;
}
string
output_file_name;
if( !settings.get( "output-file-name", &output_file_name ) || output_file_name.empty( ) )
cerr << "Error: Invalid format for 'output-file-name' (expected text)" << endl;
else
cout << "output-file-name = " << output_file_name << endl;
int
sub_period;
if( !settings.get( "sub-period", &sub_period ) )
cerr << "Error: Invalid format for 'sub-period' (expected integer)" << endl;
else
cout << "sub-period = " << sub_period << endl;
double
factor;
if( !settings.get( "factor", &factor ) )
cerr << "Error: Invalid format for 'factor' (expected floating-point)" << endl;
else
cout << "factor = " << factor << endl;
return 0;
}
Personally, though, I would go with an existing library, if possible.