sstream knowledge

Can anyone explain me whta does line 23 do??

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
  // example about structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct movies_t {
  string title;
  int year;
} mine, yours;

void printmovie (movies_t movie);

int main ()
{
  string mystr;

  mine.title = "2001 A Space Odyssey";
  mine.year = 1968;
  cout << "Enter title: ";
  getline (cin,yours.title);
  cout << "Enter year: ";
  getline (cin,mystr);
  stringstream(mystr) >> yours.year;
  cout << "My favorite movie is:\n ";
  printmovie (mine);
  cout << "And yours is:\n ";
  printmovie (yours);
  system("pause");
  return 0;
}

void printmovie (movies_t movie)
{
  cout << movie.title;
  cout << " (" << movie.year << ")\n";
} 
stringstream treats a string as a stream.
http://www.cplusplus.com/reference/sstream/stringstream/?kw=stringstream

In this case, line 23 constructs a stringstream from mystr, then uses it as an input stream to read from it into yours.year effectively letting the stream do the conversion from the string into an int.
Is there any other way to do this?
You could replace lines 22-23 with:
1
2
 
  cin >> yours.year;

I guess this is better...
Is there sth that only sstream can do and others cant???
Note that the code uses getline at line 20 to input the title rather than cin >>.
This allows the title to contains spaces. cin >> would stop at the first whitespace.

In the case of the year, cin >> could have been used directly.
Also note that the code doesn't do any error checking.
What if a non-numeric is entered for year?

stringstream inherits from istream, so it has all the same conversion functionality as istream.
Nice explanation!!! Thanx!!!
If non-numeric is entered It will say year=0;
you need to filter the user's input, e.g.:
1
2
3
4
do {
     std::cout << "enter year: ";
     std::cin >> yours.year;
} while (yours.year == 0 /*or something*/);
thanks
Topic archived. No new replies allowed.