Reputation: 4365
If you have a file format:
<int><space><int><space><char><space><char*><space><float><newline>
<int><space><int><space><char><space><char*><space><float><newline>
<int><space><int><space><char><space><char*><space><float><newline>
so for example a file can be:
12 2212 A test1ok 12.0
11 2442 B something 32.555
17 223 D sometime1test 12.0
Now, given some file, how would you check that it indeed conforms to that format?
How would you go about doing this without using external libraries other than Boost?
Upvotes: 0
Views: 286
Reputation: 94429
If the char*
part doesn't include spaces you could try using sscanf
and see whether it matches. Something like:
#include <stdio.h>
int main()
{
unsigned dummy1, dummy2;
char dummy3;
char dummy4[256];
float dummy5;
const char *str = "12 2212 A test1ok 12.0\n";
if ( sscanf( str, "%u %u %c %s %f\n", &dummy1, &dummy2, &dummy3, dummy4, &dummy5 ) > 0 ) {
// Matches
} else {
// Doesn't match
}
}
Upvotes: 1
Reputation: 70186
If using regular expressions (either C++11 or an external library like e.g. re2) isn't applicable for some reason (performance, lack of C++11, failing to build lib, company policies on deps,...) you might give a lexer generator such as lex/flex or re2C a try.
Or why not Ragel, which is among other things specifically made for the purpose of validation.
Such a generator will take an input that describes what you expect to see and what you want to happen if certain things are seen, and transform that to source code (such as C or C++) without external dependencies which compiles to a finite state machine that will parse and validate your format.
Upvotes: 0