start
name
units
2
begin
a: 12,0.7,12,12.5
b: bb, 23, 24, 10
c: cc, 23.5, 24.5, 12
d: dd, 22.5, 22.5, 13
e: 10,12,12
end
name1: abc,12, 12
name2: 12.5,12.5, 14
name3: 12.5,12.5,ab1,ab2,ab3
stop
The above is the text file sample.txt. I have to read the file and parse the above text file. How to parse each separately using C++?. Between begin and end, I have to parse each after ":" . Is there any simple logic to parse them?.
This is how you could do it:
But it's C for handling the file IO
Perhaps you can do it with filestreams too.
Code:
#include <stdio.h>
// global variable or membervariable of a class
containertypeYouWant container;
void parseFile(char * inifileName)
{
char line[1024]; // Buffer for a line
FILE * inifile;
inifile = fopen(inifileName, "rt");
while(fgets(line, sizeof(line) - 1 , inifile) != NULL)
{
// do we have to parse (are we seen begin and not seen end?)
//search line for :
//store stuff before : as identifiername in container
//parse line after : to store values
}
You'll have to work the lineparsing out yourself.
An easy way is converting the line to an std::string
Code:
std::string parseString = std::string(line);
Now you can use the search method of string
and store the information in the container
Code:
unsigned int position;
position = parseString.find(":");
if (position < parseString.size())
{
// store method of container has 2 arguments
// first is the identifier, second is the data
// store method could parse the data when it has multiple values
container.store(parseString.substr(0,position),
parseString.substr(position+2));
// ^
// forget ':' and ' '
}