How should I approach this...

I have a big project that was just assigned in class, and I want to be proactive about getting it set up, but I'm not sure if I'm thinking this out properly. We have to input information from a text file into a struct, and create a linked list out of the information using pointers. We've practiced with ifstream a lot this semester, but I'm not quite sure how I'd move the information from the text file into the struct. Can anybody give me a gentle shove in the right direction? Thanks!
Here is a short example of reading data from a text file into a struct:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

struct ExampleStruct
{
    int age;
    std::string name;

    friend std::istream &operator>>(std::istream &is, ExampleStruct &s)
    {
        is >> s.age;
        std::getline(is, s.name)
        return is;
    }
    friend std::ostream &operator<<(std::ostream &os, ExampleStruct const&s)
    {
        return os << s.name << ", age " << s.age;
    }
};

int main()
{
    std::vector<ExampleStruct> data;

    {
        std::ifstream in ("input.txt");
        ExampleStruct temp;
        while(in >> temp)
        {
            data.push_back(temp);
        }
    }

    for(std::size_t i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}
Last edited on
Well I'm late but what the hell.

You can "teach" input/output streams to read/write your structure, by overloading the relevant operators.

Below is a crude example, followed by a link to an FAQ.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <fstream>
#include <iostream>
#include <istream>
#include <ostream>
#include <string>

struct Student
{
    int id;
    std::string name;
    unsigned int age;
    float grade;
};

std::istream & operator >> (std::istream &is, Student &s)
{
    is >> s.id;
    is >> s.name;
    is >> s.age;
    is >> s.grade;
    return is;
}

std::ostream & operator << (std::ostream &os, const Student &s)
{
    os << "Student with ID " << s.id << " data:\n";
    os << "Name: " << s.name << '\n';
    os << "Age: " << s.age << '\n';
    os << "Grade: " << s.grade << "\n\n";
    return os;
}

// here we reap the rewards of the horrors above
int main()
{
    std::ifstream input_file("students.txt");
    Student ts; // Temp Student

    while (input_file >> ts) // if successfully read a student...
        std::cout << ts << std::endl; // display the student's data
}


students.txt
332
Crazy_Vixen
12
8.8

544
Minx_Deluxe
20
9.61

988
Holy_Molly
33
6.32


http://www.parashift.com/c++-faq/input-operator.html
I don't think I've quite learned about some of the elements of the codes above, and I also must use a linked list for this project. Thank you for the responses though!
Topic archived. No new replies allowed.