Getline

i was reading the tutorial in this site and found this example but i can't understand what is (Getline)
can anybody tell me what is this i know that is used in <string> but why,and How
and what is <sstream>
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";
}
Last edited on
get.ine() is a function that allows you to read input up to a specified delimite(normally a newline character) whiles cin reads up to any whitespace character.
Also,<sstream> is a header that allows you to fully use string streams.

Aceix
well can u explain more about <sstream> and what is whitespace character
closed account (3qX21hU5)
getline (cin,yours.title);

What this line is saying is it will read in all characters until it hits a \n (Newline character) which happens when you press enter. It will then put what it has read into the member yours.title

Think about this for a second. Lets look at this example of using cin instead of getline().

1
2
3
string myword;
cin >> myword;
cout << myword;


What would happen if the user entered the sentance "Hello how are you?"? Well the output would look like this

Hello


This is because cin stop at the first wightspace it see's (Which is the space right after "Hello").

Now if we used getline() instead of cin it would read up until it hits a \n character by default (It is possible to change where getline() stops by using it's second argument which is optional). So it would print out the whole sentance the user entered instead of just the first word.


As for stringstreams they are a bit of a advanced topic that you might wanna learn about later after you get more experience with how streams in general work. You can read more about them on this website just type in stringstreams into the search.
Last edited on
Thx alot
Topic archived. No new replies allowed.