Reading a large txt file

I want to know if there is another way to read a large file

Hans //name

Bachelor // study_path

WS10_11 //semester

22 // age 

and not so:

fout >> name; //string

fout >> study_path; //string

fout >> Semester ; //string

fout >> age; //int

when my file goes over more than 20 lines, should I do 20+ fouts?

Is there another way?

0
source share
2 answers

You can define a class for storing data for each person:

class Person {
public:
    std::string name;
    std::string study_path;
    std::string semester;
    unsigned int age;
};

Then you can define the stream extraction operator for this class:

std::istream & operator>>(std::istream & stream, Person & person) {
    stream >> person.name >> person.study_path >> person.semester >> person.age;
    return stream;
}

And then you can just read the whole file as follows:

std::ifstream file("datafile.txt");
std::vector<Person> data;
std::copy(std::istream_iterator<Person>(file), std::istream_iterator<Person>(),
          std::back_inserter(data));

vector. , , data.reserve(number_of_records) . , , , .

+10

Linux, mmap() , .

+1

All Articles