VOOZH about

URL: https://www.geeksforgeeks.org/cpp/getline-string-c/

⇱ getline (string) in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

getline (string) in C++

Last Updated : 23 May, 2026

getline() in C++ is a standard library function used to read an entire line of text from an input stream.
It stores the extracted characters into a string until a delimiter character is encountered.

  • Commonly used to take input containing spaces, unlike cin which stops at whitespace.
  • By default, it stops reading when a newline character (\n) is found.


Output

Geeks (Enter By user)
Geeks

Syntax

The std::getline() function is defined inside <string> header file in C++.

getline(stream, str, delim);

Parameters

  • stream: Input stream from where characters are read.
  • str: String where the input is stored after being read from the stream.
  • delim(optional): Delimiter is a character where getline stop to read the data. By default, newline character '\n' is the delimiter.

Return Value

  • It returns the reference to the input stream.

Examples of getline() Function

The following examples demonstrate the use of getline function to input from different streams in C++

Read Space Separated User Input

If we try to read the space separated string from cin stream using >> operators, it only reads the first word. Because whitespace character ' ' is the delimiter for cin. But thats not the case with getline().

Output

Harsh Agarwal (Enter by user)
Hello, Harsh Agarwal welcome to GFG !

Tokenize a String

We can use getline() function along with stringstream to split a sentence on the basis of a character.


Output

Hello Students, Welcome to GFG! (Enter by user)
Hello
Students,
Welcome
to
GFG!

In the above example, we have used getline() to read strings from the stringstream X and did it till EOF is reached. In each read, characters until the white space (individual words) are stored in the string and printed. Then the remaining words are also read in the same way.

Taking Newline as Input


Output

Please enter your id: 
10 (press enter)
Please enter your name:
Your id : 10
Hello, welcome to GfG !
Geek (Enter your name)
Hello, Geek welcome to GfG !
Comment
Article Tags:
Article Tags: