I would like to introduce a lightweight and versatile text / CSV / TSV / etc. parser library based on the ideas introduced in this thread.
Introduction
The central idea is to use the types of the output variables themselves to determine the parsing behaviour. E.g., if we associate an int with a field, an integer parsing procedure is performed.
This tight coupling between fields and output variables eliminates the need to have a preconfigured, static line format. It also allows for compact code and it reduces the burden of changing code in different places when a variable type change is desired.
All basic data types and arrays of basic types are supported. This library is type safe and does not use any dynamic memory.
Examples
If all fields are of the same type, we can extract the data using an array.
TextParser parser(", ");
int a[5];
parser.parseLine("1, 2, 3, 4, 5", a);
// `a` now contains values 1, 2, 3, 4 and 5.
If we want to change the type from int to float, we simply change the type of the output variable.
float a[5];
parser.parseLine("1, 2, 3, 4, 5", a);
// `a` now contains values 1.0f, 2.0f, 3.0f, 4.0f and 5.0f.
This also works for multidimensional arrays.
int a[2][3];
parser.parseLine("1, 2, 3, 4, 5, 6", a);
// `a[0]` now contains 1, 2 and 3, `a[1]` contains 4, 5 and 6.
If the fields have different types, we can use multiple variables.
char a[10];
int b;
double c;
parser.parseLine("one, 2, 3.4", a, b, c);
// `a` now contains "one", `b` contains 2 and `c` contains 3.4.
An end of line string can be provided to strip newlines or other symbols we do not care about.
TextParser parser(" ", ".");
char words[5][6];
parser.parseLine("This is a nice line.", words);
// `words` now contains "This", "is", "a", "nice" and "line".
Further reading
The source is available on GitHub, the code is released under the MIT Open Source license. More information can be found in the online documentation. There is also an online demo available for testing purposes.
I hope this library is of use to you. Any feedback is welcome of course.