-3

Mike 85 83 77 91 76 CSC

Mark 80 90 95 93 48 CSC

Anderson 78 81 11 90 73 BUSS

Blair 92 83 30 69 87 ECE

Suzy 23 83 30 69 87 ARC

Karlos 46 76 90 54 38 MASS-COMM

So i have this file and i am required to read the data of it and output it through the console using structs, i have managed to read Mike's Name and his scores and Faculty but that's where i am stuck, how can i continue reading ?

Here is my code

struct student {

    string name;
    int scores[5];
    string faculty;

};


void main() {

    student x;

    ifstream myfile("D:\\Test\\MIUCS.txt");

    myfile >> x.name;

    for (int j = 0; j < 5; j++) {

            myfile >> x.scores[j];
        }



    myfile >> x.faculty;


    cout << x.name << " ";

    for (int k = 0; k < 5; k++) {

        cout << x.scores[k] << " ";

    }


    cout << x.faculty << endl;


}

Hint: My Prof said to use an array of type student (the struct) which i can't really implement, any help would be appreciated thank you.

Ahmed Hassan
  • 31
  • 2
  • 9

1 Answers1

1

how can i continue reading ?

Wrap the code around reading/writing in a while loop. Keep reading and writing until there is nothing to read.

while (  myfile >> x.name )
{
   for (int j = 0; j < 5; j++)
   {
      myfile >> x.scores[j];
   }

   myfile >> x.faculty;

   // If there was any error in reading from myfile, break out of the loop.    
   if ( !myfile )
   {
      break;
   }

   cout << x.name << " ";
   for (int k = 0; k < 5; k++)
   {
      cout << x.scores[k] << " ";
   }

   cout << x.faculty << endl;
}

You can simplify the loop by moving the code for reading and writing to their own functions.

while ( myfile >> x )
  std::cout << x << std::endl;

In order to use the above, you will need to overload the operator>> function and the operator<< function as:

std::istream& operator>>(std::istream& in, student& s);
std::ostream& operator<<(std::ostream& out, student const& s);

I'll leave it to you to take it to the next step.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • This gave me only the last line (Karlos and his Scores/Faculty) – Ahmed Hassan Apr 17 '18 at 19:32
  • @AhmedHassan, that does not wound right. It shouldn't. Make sure that the `while` loop includes the lines for output. – R Sahu Apr 17 '18 at 19:35
  • i don't quite understand the overloading part if you can explain a bit more into it that would be great. – Ahmed Hassan Apr 17 '18 at 19:38
  • @AhmedHassan, if you haven't learned about operator overloading yet, you can ignore that part. When you are ready to learn about operator overloading, a good text book is the best option. The following is a very good post at SO that addresses the subject. https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading. – R Sahu Apr 17 '18 at 19:42