getline (string) in C++ (original) (raw)

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.

#include <bits/stdc++.h> using namespace std;

int main() { string name;

// Taking input from cin stream(standard
// input stream) and storing it in name
getline(cin, name);
cout << name;
return 0;

}

`

**Output

Geeks _(Enter By user)
Geeks

**Syntax

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

getline(stream, str, delim);

**Parameters

**Return Value

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().

C++ `

#include #include using namespace std;

int main() { string str;

// Read input from cin
getline(cin, str);
cout << "Hello, " << str
     << " welcome to GFG !";
return 0;

}

`

**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.

CPP `

#include <bits/stdc++.h> using namespace std;

int main() { string S, T; getline(cin, S);

// Store the string S 
// into stringstream X
stringstream X(S);

while (getline(X, T, ' '))
    cout << T << endl;
return 0;

}

`

**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

CPP `

#include #include using namespace std;

int main() { string name; int id;

// Taking id as input
cout << "Please enter your id: \n";
cin >> id;

// Takes the empty character as input
cout << "Please enter your name: \n";
getline(cin, name);

// Prints id
cout << "Your id : " << id << "\n";

// Prints nothing in name field
// as "\n" is considered a valid string
cout << "Hello, " << name
     << " welcome to GfG !\n";

// Again Taking string as input
getline(cin, name);

// This actually prints the name
cout << "Hello, " << name
     << " welcome to GfG !\n";

return 0;

}

`

**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 !