plz help...How to read text file into struct?

Hi. I have a problem with my program. I have to read a text file into a struct that has song name, song artist and song duration.

1
2
3
4
5
6
  struct playlist
{
    char title [50];
    char artist [50];
    char duration [5];
};


my file...only there are a lot more songs to read, this is just a preview.
1
2
3
4
5
6
7
8
9
10
11
12
Let It Go
Idina Menzel
4:33
Do You Wanna Build a Snowman?
Kristen Bell
4:56
All Of Me
John Legend
4:23
Let It Go
Demi Lovato
3:11


how can i read this file into this struct? and if possible can it be done with using pointers.
tnx for helping.
Last edited on
you can
It is better to use std::string for that.
But if you want to use char arrays, here is solution:
1
2
3
4
5
6
7
8
9
10
void read_playlist(std::istream& in, playlist& out)
{
    in.getline(out.title, 50);
    in.getline(out.artist, 50);
    in.getline(out.duration, 5);
}

//usage
playlist song;
read_playlist(std::cin, song);

i found a way to read line by line with pointers. now i just have to try and print it out.

1
2
3
4
5
6
7
8
9
10
while(in.getline(tmp,sizeof(tmp)))
    {
        playlist *t=new playlist;
        strcpy(t->title, tmp);
        in.getline(tmp, sizeof(tmp));
        strcpy(t->artist, tmp);
        in.getline(tmp, sizeof(tmp));
        strcpy(t->duration, tmp);
        in.ignore();
    }
Hey filipradil,

I just had some code I was working on that used exactly what you were talking about. Take a look at it here:

http://www.cplusplus.com/forum/beginner/132641/

You might benefit from using strings in your structure, as opposed to a char array; but what is a string, if not a multitude of chars ;)

You should be able to just use my code as an outline to read your text file into your structure. You can see that at the beginning of my code I initialized an array of my structure, and then my load function populates it with the lines from the .txt!
Topic archived. No new replies allowed.