getline() problem

over here in this code
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
38
// 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);
  return 0;
}

void printmovie (movies_t movie)
{
  cout << movie.title;
  cout << " (" << movie.year << ")\n";
}


getline (cin,mystr);
stringstream(mystr) >> yours.year;
why should i define a new string then use it instead of just saying
getline (cin,yours.year);
when i replace the new getline i give me an error at c++ visual studio 2010
HOWEVER it dont give any errors while using cin >> yours.year
so whats wrong with getline function over here ? does it always need a string not integer so we use string in the middle to use it ?
does it always need a string not integer so we use string in the middle to use it ?

Yes, std::getline takes a string as a second parameter so if you want to get an integer using getline, then you have to read a temporary string and convert. You're right that if all you want is an integer, then cin>> is fine. However, cin>> leaves a newline in the stream. getline on the other hand reads everything up to and including the newline (assuming you didn't use the other form that takes in a delimiter). I believe that they used getline in this example for symmetricity of the input statements (and for not having to worry about cleaning up the newline).
Topic archived. No new replies allowed.