Tell me why

Hi,
I have a question about the line marked with a comment in the code below.
why did author use stringstream() instead of cin ?
source: tutorial-->data structures

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
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct movies_t {
  string title;
  int year;
} films [3];

void printmovie (movies_t movie);

int main ()
{
  string mystr;
  int n;

  for (n=0; n<3; n++)
  {
    cout << "Enter title: ";
    getline (cin,films[n].title);
    cout << "Enter year: ";
    getline (cin,mystr);
    stringstream(mystr) >> films[n].year;  //This line
  }

  cout << "\nYou have entered these movies:\n";
  for (n=0; n<3; n++)
    printmovie (films[n]);
  return 0;
}
The method used consumes the entire line that the user enters, including anything after the year and the newline character. In other words, the user could enter
2014 and here is some junk
and it would work. If you used cin >> films[n].year then it would consume only the year and not the trailing junk or the newline.

By the way the construct is interesting. It creates an anonymous temporary stringstream. In other words line 24 is like doing this:
1
2
3
4
{
    stringstream tmp(mystr);
    tmp >> films[n].year;
}

Topic archived. No new replies allowed.