a firstworks project
Rudiments
About Documentation Download Licensing News

Using the parameterstring class

Sometimes a function needs to take an arbitrary set of parameters. For example, a function for connecting to a database may need host, port, socket, username and password, any of which could be omitted depending on the database. Though C++ support methods which take an arbitrary number of parameters, sometimes it is more convenient to for the method to accept a single string parameter with name/value pairs in it instead.

The parameterstring class provides methods for parsing and accessing a parameter string of the following form:

name1='value1';name2='value2';name3='value3'

The single quotes are optional. If a parameter needs to contain a single quote, then it can be escaped as follows:

name='\'value\''

Backslashes can be similarly escaped:

name='\\value\\'

The delimiter between parameters defaults to a semicolon, but can be changed using the setDelimiter() method.

The following example parses a parameter string, accesses individual values, clears the string, sets a different delimiter, and parses another string.

#include <rudiments/parameterstring.h>
#include <rudiments/stdio.h>

int main(int argc, const char **argv) {

	parameterstring	ps;

	// parse a parameter string with the default semicolon delimiter
	ps.parse("host=localhost;port=9000;user='testuser';password='testpwd'");

	// access individual values
	stdoutput.printf("host:     %s\n",ps.getValue("host"));
	stdoutput.printf("port:     %s\n",ps.getValue("port"));
	stdoutput.printf("user:     %s\n",ps.getValue("user"));
	stdoutput.printf("password: %s\n\n",ps.getValue("password"));


	// clear and parse with a different delimiter
	ps.clear();
	ps.setDelimiter(',');
	ps.parse("name=hello,value=world");

	stdoutput.printf("name:  %s\n",ps.getValue("name"));
	stdoutput.printf("value: %s\n",ps.getValue("value"));
}
Copyright 2017 - David Muse - Contact