0

I am trying to understand the way the getline function works. In the following example, I enter "Hello There!" and use the cin object to take in input from the user. I do this to demonstrate that the cin will stop reading in input after a space is entered by the user.

Below this I am using the getline function to demonstrate the correct way to do this, but don't understand why it outputs the way that it does on the terminal window. Please explain. Thank you.

#include <iostream>
using namespace std;

int main() 
{
  string greeting;
  // cout << "Enter \"Hello There!\": ";
  cin >> greeting; // Once the cin object sees a space, it stops. This is why the cin object only grabs the first word.
  cout << "greeting: " << greeting << endl;
  cout << "Enter \"Hello There!\": ";
  getline(cin, greeting);
  cout << "greeting: " << greeting << endl;

  return 0;
}

Source Code: https://replit.com/@gurbanishvili/getline-for-Strings#main.cpp

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • 2
    Firstly, the behaviour is not specific to `cin`. All stream classes share behaviour. Then, not all operations skip whitespace or terminate on whitespace. For reference (though maybe hard to understand for a beginner), there's cppreference.com, where you can look up the specification for `getline()`. As a new user here, please also take the [tour] and read [ask]. – Ulrich Eckhardt Aug 10 '21 at 20:42
  • 1
    How does it output? How do you think it should output, and how is that different? Why do you think it should output that way? – Karl Knechtel Aug 10 '21 at 20:42
  • Does https://stackoverflow.com/questions/33356615/getline-is-returning-nothing-but-blank answer your question? I found it by putting `c++ getline blank` into a search engine. (I am guessing at your answers to the questions I asked.) – Karl Knechtel Aug 10 '21 at 20:44

0 Answers0