getline with struct?

Hi I am trying to create a collection array of videos from a text file that contains the year and name of the movies,
eg

1994
tron
2015
mad max
1997
pulp fiction
...

I can't seem to work out how to grab more than one word when populating the title.
I have tried to use getline(infile, collection[i].title); in place of the infile>> however that gives me bad output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct data
{
int year;
string title;
}colection[100];
		
ifstream infile;
infile.open ("videos.txt.");

for(int i = 0; i < 100 && !infile.eof(); i++) 
{
        infile >> collection[i].year;  
	infile >> collection[i].title;//works with no white spaces eg "tron" 
}


Thanks guys, if you need more info let me know.
You're mixing formatted and unformatted extraction. When doing so, you often need to get rid of the whitespace left in the stream after a formatted input operation prior to using an unformatted extraction operation.

By the way, looping on eof is a logical error the way you're doing things.


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
42
#include <fstream>
#include <iostream>
#include <string>

struct movie
{
    int year;
    std::string title;
};

// extract a movie from a stream:
std::istream& operator>>(std::istream& is, movie& m)
{
    // extract the year:
    is >> m.year;

    // remove the whitespace between year and title:
    is >> std::ws;

    // extract the title:
    getline(is, m.title);

    return is;
}

const unsigned collection_max = 100;

int main()
{
    std::ifstream in("video.txt");

    movie collection[collection_max];

    unsigned n_records = 0;
    while (n_records < collection_max && in >> collection[n_records])
        ++n_records;

    std::cout << n_records << " records read:\n";

    for (unsigned i = 0; i < n_records; ++i)
        std::cout << '\t' << collection[i].year << ' ' << collection[i].title << '\n';
}
Thanks a lot! I'll fiddle with my logic a bit. Adding std::ws to the end of the input before getline works. :)
Cheers.
Topic archived. No new replies allowed.