Question

I'm trying to create a simple parser and a small text file which follows the following structure:

Variable_name = Value;

VARIABLE_2 = SECOND_VALUE;

Found methods that work, however, use many librarys like Boost. I wonder if you can make a simple, preferably with only the librarys of STD.

Thanks, Bruno Alano.

Was it helpful?

Solution

If your format will be staying like you have listed, and there will be no spaces in either the variable names or the values, this is can be done easily using a combination of std::string and std::istringstream. You could simply do the following:

//assume we have an open ifstream object called in_file to your file
string line;
getline(in_file, line);

while (in_file.good())
{
    char variable[100];
    char value[100];
    char equals;

    //get rid of the semi-colon at the end of the line
    string temp_line = line.substr(0, line.find_last_of(";"));
    istringstream split_line(temp_line);

    //make sure to set the maximum width to prevent buffer overflows
    split_line >> setw(100) >> variable >> equals >> value;

    //do something with the string data in your buffers

    getline(in_file, line);
}

You can change the types of variable and value to properly fit your needs ... they don't need to be char buffers, but can be any other type provided that istream& operator>>(istream&, type&) is defined for the data-type you want to use.

OTHER TIPS

If variables and values cannot contain equal signs or semicolons and you can assume the file will always be well-formed this is trivial to do.

Grab everything until you reach a semicolon. Split the string at the = sign. The first part is your variable name. The second part is the value.

If you have to deal with comments, string literal values (that may contain = or ;) this is NON-TRIVIAL and you should use boost.Spirit.

If you're wondering how to split a string, there's many questions asked about the topic and a particularly good one is: Split a string in C++?

Its basically not dissimilar to an INI file.

Quick search comes up with this: http://code.google.com/p/inih/

Which has minimal dependencies.

If you need to, it is probably pretty easy to strip out the section handling.

You'd need to add in handling for the semicolons though, which are normally the start of comments in INI files.

Its a starting point, at least.

The really short (C-style) method would be something like:

scanf("%s = %[^\n]", variable_name, value);

You could use the lemon parser generator, it generates a file with no dependencies beside stdlibc. Here is a good starting tutorial.

As a scanner, I prefer re2c, which is also public domain.

You could wrap the yyparse() function in a C++ class, if you really need C++.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top