stringstream question

Can anyone please tell me what is the line
stringstream(mystr) >> yours.year;
doing in this program.
I will be thankful if you can give me an easy example which uses only this.
stringstream(mystr) >> yours.year;



#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);
return 0;
}

void printmovie (movies_t movie)
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
Last edited on
It is creating a stringstream by passing a string to the constructor, then putting it in yours.year.
I would expect it to only read the integer-portion...for example, inputting "10abc and 5 more words blah you see!" will be stored in mystr, and a temporary stringstream will be constructed containing that string, but then an int will be extracted from it putting only 10 into yours.year.
Can you please give any easy example of using stringstream(mystr) >> yours.year;?
stringstream( "123 abcd" ) >> variable; gives the value 123 to the variable.

An example with named objects could be easier:
1
2
3
4
string myString = "123"; // string with some text in it
int number; // number which needs a value
stringstream myStringStream( myString ); // stream created with the contents of the string
myStringStream >> number; // giving the value of 123 to the number 

The same result could be achieved with an unnamed stringstream object:
1
2
3
string myString = "123"; // string with some text in it
int number; // number which needs a value
stringstream ( myString ) >> number; // giving the value of 123 to the number from a stream created with the contents of the string 

Last edited on
Thank you bazzy !
Topic archived. No new replies allowed.