I need to read a text file that contains data of the following type:

John Doe 333222333 01/01/80 M
PHY301 2005 Fall A
PHY401 2005 Fall B
PHY531 2006 Spring A
John Doe 333222333 01/01/80 M
PHY501 2005 Fall A
PHY301 2005 Fall B
PHY431 2006 Spring A
John Doe 333222333 01/01/80 M
PHY301 2005 Fall A
PHY401 2005 Fall B
PHY531 2006 Spring A

So in other words, the first line will contain whitespace delimited STRINGs. (firstname lastname ssn dob sex) and the lines following it will contain course information (until another student is found) for the student on the first line.

When I only had to deal with one student, I did it like this:

in >> fName >> lName >> ssNum >> dob >> gen;
     
     while (in >> cid >> ytt >> stt >> score)
.... (store records)

and so on till the end of the file... however I have tried different things for HOURS :( and I cannot figure out a good way to do this.

PS. I am allowed to do the following check: if a line starts with PHY, then it must be a course.
My main problem is that I do not know how to split the getlined string into separate variables and also how to check for PHY in the string.

Thanks for any help you can provide.

you need to read in a complete line at one time ( use std::getline ) and then extract the information from it. a simple way would be to use a std::istringstream

the format of your text file is not well thought out. the simplest would be to leave an empty line (containing only a '\n') after information for each student. that way, you only need to check for an empty string.

if that is not possible, you could do this: if the line you have read contains five whitespace delimited strings, then it is student information; if there are only four, it is course information. you can easily see why this would break if additional fields need to be added later.

Thank you for your help. This is for a school project, so I have to follow the format given.

Actually, I forgot to mention one thing. I am allowed to check if a line contains PHY in it - then it's a course (all the courses will start with the same 3 characters).

If you could, please give me an example of using istringstream. My main problem is how to break up the getlined string into different separate variables.

Thank you very much.

#include <sstream>
#include <iostream>

int main()
{
  std::string line = "how now brown cow" ;
  std::istringstream stm(line) ;
  std::string str ;
  while( stm >> str ) std::cout << str << '\n' ;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.