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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With