Playing with getline()

Hello, I was playing around with getline() seeing what I can and can't do with it and tried this:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
    string text, input;
    cout << "Please input text" << endl;
    cin >> input;
    getline(cin,text);
    cout << text;

    return 0;
}


I inputted "hello i am" and saw that it got truncated to " i am", I don't understand why this happened. I was expecting for the object cin to be saved over to the text variable.

I wasn't trying to do anything specific, as I said, I was just playing around trying to see different ways I can use getline. I know that to properly use getline(), from my code, you'd remove the cin >> input; line.
Last edited on
getline starts reading from the where cin>> left off.
@Peter87 The stream concept pops up everywhere, but I never really understood it. Now I understand stream a little more, thank you!

After realizing how stream is used in my example, I see that there are more uses to cin than I had thought it would be used for. Up until now, I just thought that cin only prompts for user input. I would only use single words like "hello" for input, so I never realized that it could output the rest of the string separately.

1
2
3
4
5
    
    cin >> input; 
    cout << input << endl; 
    cin >> input;
    cout << input << endl;
Last edited on
You can type input to the program at any time. When you read from cin it will read from the input that you have already inputted. If there is not enough input available it will wait until there is.

Reading input from the user with cin is done the same way as reading input from a file using ifstream.
ifstream might also have to wait, not for the user, but for the data to be read from disk into main memory.
Last edited on
Topic archived. No new replies allowed.