0

Im trying to read in data using both getline and cin from a file. But, it only reads in the first line
and it leaves everything else empty and/or gives garbage values.

output:
John Brown grades: 73 57 94
grades: 0 32767 1252009800
grades: 0 0 1263344400

/*
data.txt
John Brown
73 57 94
Alex Smith
85 85 85


*/


#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
#include <string>

using namespace std;

class grades
{
   public:
      int quizzes[3];
      int average;
};

class student
{
   public:
      grades q;
      string name;
};


int findaverage(int *);
void readindata(student *, int &);

int main()
{
   student students[30];
   int size = 0;

   readindata(students, size);

   for(int i = 0; i < size + 1; i++)
   {
      cout << students[i].name << " grades: ";
      int counter = 0;
      while(counter < 3) //only the quizzes
      {
         cout << students[i].q.quizzes[counter] << ' ';
         counter++;
      }

      cout << endl;
   }

   return 0;
}

void readindata(student *a, int &size)
{
   ifstream file;
   file.open("data.txt");
   if(!file)
   {
      cout << "error..." << endl;
      abort();
   }

   while(file.good())
   {
      getline(file, a[size].name);

      int counter = 0;
      while(counter < 3)
      {
         file >> a[size].q.quizzes[counter];
         counter++;
      }

      size++;
   }

   file.close();
}
2
Contributors
1
Reply
3
Views
4 Years
Discussion Span
Last Post by vmanes
0

After you read in the grades with the extraction operator ( >> ), a newline is left on the input stream. When you then use getline again, it sees the newline and quits.

You need to remove that newline. Perhaps

file.ignore( 10, '\n' );

This will throw away up to 10 characters, or until a newline is encountered, whichever comes first. Then your getline statement sees a fresh line.

Your loop control there is going to give you a size value one larger than what you actually read in. The while statement won't know the input's gone bad till you tried to read past end of file, at which point you increment size anyway.

You can use the input statement to control the loop action, like

while( getline(file, a[size].name) )
{
    //read the grades

    //increment size
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.