简体   繁体   中英

How to open a file and store data into a linked list structure

I have a function buildList where I am supposed to open a given file named "studentFile1.txt" and use an overloaded operator to read in data from a file. I am supposed to save all the data as a linked list where each student's info is a node. But I can't seem to open the file for some reason. This is the function buildList

{
    ifstream file;
    file.open("studentFile1.txt");

    Student temp;     // temporary struct Student object

    if (!file)
        cout << "Can not open file\n";
    while (file >> temp)
    {
        if (list.insert(temp) == false)
            cout << "Insert did not work\n";
    }
}

And this is the overloaded operator >> function

istream &operator>>(istream &istr, Student &obj)
{
    ifstream file;
    file.open("staudentFile1.txt");

    if (!file)
        cout << "Can not open file.\n";
    while (file)
    {
        istr >> obj.id;
        istr.ignore();
        istr.getline(obj.name, 50, '\n');
        istr >> obj.gpa;
        istr >> obj.major;
    }

    return istr;
}

When I call the buildList function it just says "Can not open file" twice. What am I doing wrong?

When you write file.open("studentfile1.txt") the executable assumes that the file is in the same directory as the executable. Check that they are. As for the remainder of the code you have already opened the file outside the operator overload you shouldn't do it again. Also remove the while loop as it will keep reading until the end of the file so you will read a single record and all the others would be empty.

 istream &operator>>(istream &istr, Student &obj)
    {
            istr >> obj.id;
            istr.ignore();
            istr.getline(obj.name, 50, '\n');
            istr >> obj.gpa;
            istr >> obj.major;
    
        return istr;
    }
int main(){
   Student s;
   ifstream file;
   file.open("staudentFile1.txt");
    
   if (!file)
            cout << "Can not open file.\n";
   else {
       while(file>>s)list.insert(s);
   }
   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM