A simple method for a simple analyzer

I am trying to create a simple parser and a small text file that follows the following structure :

Variable_name = value;

VARIABLE_2 = SECOND_VALUE;

Found methods that work , however, use many libraries , such as Boost. I wonder if you can make it simple, preferably only with STD libraries .

Thank you Bruno Alano.

+4
source share
5 answers

If your format remains as you indicated, and there are no spaces in the variable names or values, this can be done easily using a combination of std::string and std::istringstream . You can 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 variable and value types to suit your needs ... they don't need to be char buffers, but can be any other type as long as istream& operator>>(istream&, type&) defined for the data type you want use.

+3
source

If the variables and values ​​cannot contain the same signs or semicolons, and you can assume that the file will always be well formed, this is trivial.

Grab everything until you reach the semicolon. Divide the line by the = sign. The first part is your variable name. The second part is the meaning.

If you have to deal with comments, string literals (which may contain = or ; ), this is NOT-TRIVIAL , and you should use boost.Spirit .

If you are wondering how to break a string, there are many questions about the topic and especially good ones: Split a string in C ++?

+3
source

Basically it is no different from an INI file.

Quick Search: http://code.google.com/p/inih/

which has minimal dependencies.

If you need it, it's probably pretty easy to remove from the processing section.

You will need to add processing for semicolons, although this is usually the beginning of comments in INI files.

Its starting point, at least.

+1
source

You can use the lemon syntax generator , it generates a file with no dependencies next to stdlibc. Here is a good starting tutorial.

As a scanner, I prefer re2c , which is also publicly available.

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

+1
source

The shortest (C-style) method will look something like this:

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

All Articles