A little advanced question involving fstream.

Hey guys. I have been taught how to read a text file with a set of data from the first line until the last line, each set of data represents different information of an object.
Currently I want to read the background info of the project first locating in the first line of text file before moving into second and subsequent lines which contains the set of data for the given project.
Here is the example text file:
--------------//Beginning of text file
5 dbbac
15511 dabac
15112 dcbcd
14251 dbbac
-------------//End of text file

And it should read and display the data on screen as follows:
----------------------
Question 1 2 3 4 5
Answer d b b a c

ID Score(%)
15511 80.0
15112 60.0
14251 100.0
----------------------

Ignore the marks scored,
How should I implement the code to read the non-uniform data from the text file? Advice and recommendation are deeply appreciated!
Last edited on
It's hard to see how you're going about doing things. Can you post your code involving reading from the file and/or said object for which the data is on the file?
Just read the first line, which is special. Then loop the remaining lines.

You read the first line to get the number of questions and correct answer:
1
2
3
int numberOfQuestions;
string correctAnswers;
strm >> numberOfQuestions >> correctAnswers;


Then you loop round the rest whilst the stream remains valid (i.e. until it reaches the end; easiest to base this on the state of the stream.

1
2
3
4
5
6
7
int ID;   // or:  string ID; it's not actually numeric;
string studentAnswer;
while ( strm >> ID >> studentAnswer )
{
    // any processing to do on studentAnswer
    // any output of this student's data
}


Alternatively, you can use getline(strm, .... ) to put the whole line in a string; then stringstream this into the variables you want.
@hoogo
It's hard to see how you're going about doing things. Can you post your code involving reading from the file and/or said object for which the data is on the file?

I'm sorry I haven't write a single line of code because I know that it won't work no matter how hard I tried given that I never seen this situation before. I appreciate your attempt to help out.

@lastchance
Wow that's something new to me and exactly what I seek for. Thanks for such short and precise answer! I appreciate your constructive help and have a nice day!
@ structJason
No worries, glad to see you've found what you were looking for!
Have a nice day!
Topic archived. No new replies allowed.