1

My code is meant to receive a data file and store it into an array of structures. As of now, the code stores data for the first student, but fails to get anything for the consecutive students. How would i get the code to store the data for the rest of the file into consecutive arrays of the structure?

#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;

struct student{
string fname, lname, id, classname[20];
char grade[20];
int units[20], unitstaken, unitscompleted, numberofclasses;
float gpa, points[20], avg;
};

void doesitrun(ifstream& fin, string& filename);
void readit(student& temp, ifstream& fin);
int Read_List(student& child, int size);

int main(){
int i = 0;
ifstream fin;
string filename;
student u[20];
doesitrun(fin, filename);


readit(u[i], fin);
Read_List(u[i], 20);


}

void doesitrun(ifstream& fin, string& filename){
bool trueorfalse;
cout << "Enter file name along with location: ";
getline(cin, filename);
cin.ignore(20, '\n');
fin.open(filename.c_str());
if (fin.fail())
    trueorfalse = false;
else
    trueorfalse = true;
while (trueorfalse == false){
    cout << "File does not run. Please try again. " << endl;
    fin.close();
    cout << "Enter file name along with location: ";        

    getline(cin, filename);
    fin.open(filename.c_str());
    if (fin.fail())
        trueorfalse = false;
    else
        trueorfalse = true;
}

}

void readit(student& temp, ifstream& fin){

int i = 0;
getline(fin, temp.lname, ',');
cin.ignore();
getline(fin, temp.fname);
fin >> temp.id;
fin >> temp.numberofclasses;
fin.ignore(10, '\n');

for (i = 0; i < temp.numberofclasses; i++){

getline(fin, temp.classname[i]);
fin >> temp.grade[i];
fin >> temp.units[i];
fin.ignore(10, '\n');
}

}

int Read_List(student child[], int size)
{
ifstream    fin;
int     i = 0;

readit(child[i], fin);
while (!fin.eof())
{
    i++;
    if (i >= size)
    {
        cout << "Array is full.\n";
        break;
    }
    readit(child[i], fin);
}
fin.close();
return i;
}
Sport
  • 8,570
  • 6
  • 46
  • 65
Ammar
  • 31
  • 7

1 Answers1

1

There could be other problem too related to file format, but how about starting with Why is iostream::eof inside a loop condition considered wrong ?

Then try something like,

struct student 
{
    //...
    friend std::istream & operator >> ( std::istream& is, student& temp ) ;
}

std::istream & operator >> ( std::istream& is, student& temp )
{
    readit( temp , is );
    return is ;
}

And in Read_List,

while ( fin >> child[i] )
{
   i++ ;
   // ...
}
Community
  • 1
  • 1
P0W
  • 46,614
  • 9
  • 72
  • 119