954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Parsing a text file in c++

i want to parse a file,my problem is in lines 2,3,4 of each person(every 4line make a person from my class person)numbers of my variables in lines 2,3,4 changed.i want to push_back each of variable in line 2 in a vector until it comes to "\n",i want to continue this work(make person)until the cursor comes to "---------------"
this is a sample of my text file:

David bekham
105700 -6.42372e+006 12345
mac vaio dell lenovo
50 30 40
Messi
-105700 1.49887e+007
toshiba acer dell asus
50 70 53
C.Ronaldo
6.39639e+006 21415
msi dell lenovo
30 42 14
---------------

more details: http://i52.tinypic.com/2j0nn8g.png

messengerman
Newbie Poster
2 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

I would use getline() to read in each line as a std::string. When it comes to those lines which are variable, read the string into a stringstream and use the >> extraction operator to pull out what you need.

That way you can compare each line with "----------" to see when to stop.

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

Is it reasonable for you to print file as binary file instead of text file?
This way you can read and write entire structure.
But yeah if you need a text file only then you can :
Instead of ------------ you can use some character which you won't use anywhere.

read a line using getline and compare it with above symbol.
If it is not true read thrice and each time separate strings.
Then you can use atoi() and atof()

Vinayak

vinayakgarg
Junior Poster in Training
83 posts since Jan 2010
Reputation Points: 19
Solved Threads: 17
 

how can define that when cursor comes to specific char then break from loop?what is the clause of loop?

messengerman
Newbie Poster
2 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

Take a substring (2 characters) of the string you read in using getline, and compare it to "--" (unless you think your professor will put in aberrant lines to test your program. Or if you know the number of dashes ahead of time, compare it with that.

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: