1

I have this struct to hold student information:

struct student_info {
    int year;
    string course_name;
    int course_id;
    string student_name;
    int student_id;
};

And I read in from the file like this:

    ifstream infile ("info.txt");

    while(infile >> year >> course_name >> course_id >> student_name >> student_id) {
        // do stuff
    }

I was wondering if there is a way to shorten the while loop condition and still be able to read in all that data? I feel like it's too long

Biffen
  • 5,354
  • 5
  • 27
  • 32

3 Answers3

4

I was wondering if there is a way to shorten the while loop condition and still be able to read in all that data?

You'll have to read the individual members of the struct no matter what. You can simply the while statement by overloading operator>>(std::istream&, student_info&).

std::istream& operator>>(std::istream& in, student_info& info)
{
   in >> info.year;
   in >> info.course_name;
   in >> info.course_id;
   in >> info.student_name;
   in >> info.student_id;
   return in;
}

and use it as:

ifstream infile ("info.txt");
student_info info;

while(infile >> info) {
    // do stuff
}
R Sahu
  • 196,807
  • 13
  • 136
  • 247
0

There are a number of ways you could shorten the line. For example, you could read each line in its entirety and then parse out each field of each line:

std::string line;
ifstream infile ("info.txt");


while(std::getline(infile,line)) {
    std::istringstream iline(line);

    int year;
    std::string course_name;
    int course_id;
    std::string student_name;
    int student_id;

    //omitting error checking for brevity
    iline >> year;

    //do stuff with year

    iline >> course_name;
    //etc..

}
Daniel
  • 1,271
  • 4
  • 15
-1

You can use the method eof() to check if EndOfFile has reached. I have modified your code to read student_info structure and append to the vector.

ifstream infile("info.txt");
vector<student_info> vs;

while (!infile.eof())
{
    student_info st;
    infile >> st.year;
    infile >> st.course_name;
    infile >> st.course_id;
    infile >> st.student_name;
    infile >> st.student_id;
    vs.push_back(st);
}
D Giri
  • 24
  • 2
  • [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Biffen Feb 11 '18 at 07:26