简体   繁体   中英

How can I save one column of data from a text file into an array in C++?

The problem...... This is followed by the student id and then several marks student scored in various assessments, one per line. A small segment of the file might look like the following,,,,

2
S1234567
55
70
4
S2222222
96
67
88
88

So, according data presented in this file, the first student has 2 scores, student id is S1234567, and the assessment scores are 55 and 70. The second students has 4 scores, student id is S2222222, and the assessment scores are96, 67, 88 and 88.

So what I want to know is if I was asked to save this to an array and display in a meaningful way can I save it to a 2d array? Because number of columns changes in each row...

S1234567     55, 70
S2222222     96, 67, 88, 88

Is this possible?

The simplest thing would be to make std::vector<std::vector<int>> , where the first element in each std::vector<int> is student's id.

Better would be to use a Student class:

class Student
{
public:
    int id;
    std::vector<int> scores;

    ...
};

std::vector<Student> students;

You can easily overload >> and << operators for this class and much more for the future.

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