How to Use getline in C++: Syntax and Examples
In C++, use
std::getline to read an entire line of text from an input stream like std::cin. It reads characters until it finds a newline, storing the result in a std::string. This is useful for reading input with spaces.Syntax
The basic syntax of std::getline is:
std::getline(input_stream, string_variable);
Here, input_stream is usually std::cin or any input stream, and string_variable is a std::string where the line will be stored.
Optionally, you can specify a delimiter character to stop reading before it:
std::getline(input_stream, string_variable, delimiter);
cpp
std::getline(std::cin, line);
std::getline(std::cin, line, '\n');Example
This example shows how to use std::getline to read a full line of text including spaces from the user and then print it.
cpp
#include <iostream> #include <string> int main() { std::string line; std::cout << "Enter a full line of text:\n"; std::getline(std::cin, line); std::cout << "You entered: " << line << std::endl; return 0; }
Output
Enter a full line of text:
Hello world from C++
You entered: Hello world from C++
Common Pitfalls
One common mistake is mixing std::cin >> with std::getline without clearing the input buffer. The >> operator leaves the newline character in the input, so std::getline reads an empty line immediately.
To fix this, use std::cin.ignore() to discard the leftover newline before calling std::getline.
cpp
#include <iostream> #include <string> int main() { int number; std::string line; std::cout << "Enter a number: "; std::cin >> number; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Clear newline left in buffer std::cout << "Enter a line of text: "; std::getline(std::cin, line); std::cout << "Number: " << number << std::endl; std::cout << "Line: " << line << std::endl; return 0; }
Output
Enter a number: 42
Enter a line of text: Hello after number
Number: 42
Line: Hello after number
Quick Reference
- Function:
std::getline - Purpose: Read a full line from input stream into a string
- Parameters: input stream, string variable, optional delimiter
- Common use: Reading lines with spaces from
std::cin - Remember: Use
std::cin.ignore()after>>operator beforestd::getline
Key Takeaways
Use std::getline to read entire lines including spaces from input streams.
Always store getline input in a std::string variable.
If mixing with std::cin >>, call std::cin.ignore() before getline to avoid empty input.
You can specify a delimiter character to stop reading before it.
getline reads until newline by default, making it ideal for line-based input.