[Solved] How to read an input from a file one at a time similar to reading input from console using cin/scanf in c++?


As a first approximation, I’d make the most minimal changes necessary to the code that makes you happy:

std::ifstream infile("filename");

for(int i = 0; i <CLASS_SIZE; i++)
{
  for(int j = 0; j <10 ; j++)
    {          
        // scanf("%d", &grade);
        infile >> grade;
        studentsInClass[i].setGrade(j,grade);
    }  
}

Given that you know the exact number of grades for each student, you gain little (if anything) from using getline. That would be useful primarily if the input was line-oriented. For example, consider an input file like this:

91 92 85 58 87 75 89 97 79 65 88 
72 81 94 90 61 72 75 68 77
75 49 87 79 65 64 62 51 44 70

As it stands, you still apparently want this read as 3 students with 10 grades apiece, so the last grade on the first line (the 88) belongs to the second student, not the first.

Using getline and then parsing each line individually would make sense if you wanted this input data interpreted as the first student having 11 grades, and the second student 9 grades (and the third 10 grades).


That covers the question you asked, but I’m still not particularly happy about the code. Personally, I’d prefer to write a student class that knew how to read its own data from a stream:

class student { 
    std::vector<int> grades;
public:

   // other stuff, of course.

   friend std::istream &operator>>(std::istream &is, student &s) {
       int grade;
       for (int i=0; i<10; i++) {
           is >> grade;
           s.grades.push_back(grade);
       }
       return is;
    }
};

Then when we want to read data for multiple students, we’d do something like this:

std::vector<students> the_class;
std::ifstream infile("grades.txt");

for (int i=0; i<CLASS_SIZE; i++) {
    student s;

    // use `operator>>` above to read all 10 grades for one student.
    infile >> s;
    the_class.push_back(s);
}

solved How to read an input from a file one at a time similar to reading input from console using cin/scanf in c++?