Here is the code:
// pointers to structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct movies_t {
string title;
int year;
};
int main ()
{
string mystr;
movies_t amovie;
movies_t * pmovie;
pmovie = &amovie;
cout << "Enter title: ";
getline (cin, pmovie->title);
cout << "Enter year: ";
getline (cin, mystr);
(stringstream) mystr >> pmovie->year;
cout << "\nYou have entered:\n";
cout << pmovie->title;
cout << " (" << pmovie->year << ")\n";
return 0;
}
Taken from http://www.cplusplus.com/doc/tutorial/structures/. I was hoping I could get clarification on a few things.
-
What is
getlineand how does it work? I tried looking up the documentation, but I’m still having trouble understanding. Also, what exactly iscinand how is it being used withgetline? -
If I understand correctly,
pmovie->titleessentially says thatpmoviepoints to the membertitleof the objectamovie? If so, and it’s not already clear from the explanation to #1, how doesgetline (cin, pmovie->title)work? -
Now this
(stringstream) mystr >> pmovie->yearis giving me the most trouble. What is astringstream, and are we using it like we would cast a double as a int, for example?
Thank you all!
The
getlinefunction reads a line from aistream. Thecinstream refers to your standard input stream, the one you would normally get input from. It is being passed togetlineto tell it which input stream to get a line from.The
getlinefunctions reads a line fromcinand stores it inpmovie->titlewhich is passed by reference.A
stringstreamis a class that makes a string act like a stream. This is kind of confusing syntax (C-style cast) that makes it a bit harder to understand what it is happening. Basically, a temporarystringstreamis created and initialized with the contents ofmystr. Astringstream, when initialized with a string, gives you a stream from which you can read those contents. The>>operator reads from an output stream, in this case, intopmovie->year, which is again passed by reference.By the way, it seems to me like you’re trying to understand unusually complex and confusing uses without yet understanding the more basic uses of these objects. That’s a very hard way to learn.