简体   繁体   中英

Read from text file with delimiter

I have a text file with an index of students that looks something like this:

Anna Baker
Class 1B
Long description text about the student lorem ipsum dolor sit amet, consetetur sadipscing elitr.
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt.
Lorem ipsum dolor sit amet.
Lorem ipsum dolor sit amet.
Lorem ipsum dolor sit amet, consetetur sadipscing elitr.
#####
Rick Bell
Class 2A
Long description text about the student lorem ipsum dolor sit amet.
At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. 
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor.
#####
etc.

I have a class Student and I need to extract the information from the text file and put it in student objects.

class Student{
private:
  string name;
  string class;
  string description;
}

Name and class worked fine so far but I'm struggling with extracting the description text. "#####" serves as a delimiter. I use:

while (???){
   getline(inFile, word3);
   word3=word3.substr(0,word3.find(delimiter));
}

I need a while loop to read all the lines up to the delimiter and I can't find the right statement for it. Can you help me?

Quick look to cpp reference suggets that the return value of std::string::find is std::string::npos when not foud. So you can use something like

bool continue = true;
while (continue)
{
   getline(inFile, word3);
   continue = word3.find(delimiter)) == std::string::npos;
 //do something else
}

You can use ifstream to read file, with

std::ifstream student_file("file.txt");

You can read file line by line using,

string info;
if(student_file.is_open()){
   while( getline(student_file, info) ) {
        if( info == "####")
           continue;
        else {
                //this is student info
        }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM