sstream knowledge

Jul 28, 2013 at 3:00pm
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";
} 
Jul 28, 2013 at 3:08pm
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.
Jul 28, 2013 at 3:10pm
Is there any other way to do this?
Jul 28, 2013 at 3:14pm
You could replace lines 22-23 with:
1
2
 
  cin >> yours.year;

Jul 28, 2013 at 3:18pm
I guess this is better...
Is there sth that only sstream can do and others cant???
Jul 28, 2013 at 3:26pm
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.
Jul 28, 2013 at 3:30pm
Nice explanation!!! Thanx!!!
Jul 28, 2013 at 3:31pm
If non-numeric is entered It will say year=0;
Jul 28, 2013 at 4:37pm
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*/);
Jul 28, 2013 at 8:41pm
thanks
Topic archived. No new replies allowed.