Reading a Full Line with std::getline()

How can I read a full line of input including spaces?

Reading a full line of input, including spaces, is best done with std::getline().

Unlike the >> operator, which stops at spaces, std::getline() reads until it encounters a newline character, capturing all spaces in between. Here is an example:

#include <iostream>
#include <string>

int main() {
  std::string input;
  std::cout << "Please provide input: ";
  std::getline(std::cin, input);  
  std::cout << "Input extracted: " << input;
}
Please provide input: Hello World from C++
Input extracted: Hello World from C++

In this code, std::getline() reads everything the user types until they press Enter, storing the entire input line in the input string.

Handling Different Delimiters

If you need to use a custom delimiter instead of the default newline character, you can specify the delimiter as a third argument to std::getline():

#include <iostream>
#include <sstream>
#include <string>

int main() {
  std::string input = "Hello,World,from,C++";
  std::istringstream stream(input);
  std::string word;

  while (std::getline(stream, word, ',')) {  
    std::cout << "Extracted: " << word << '\n';
  }
}
Extracted: Hello
Extracted: World
Extracted: from
Extracted: C++

In this example, std::getline() reads from the std::istringstream stream and uses a comma as the delimiter, extracting words separated by commas.

Benefits of Using std::getline()

  • Reads entire lines, including spaces
  • Allows for custom delimiters
  • More control over input handling compared to >> operator

Using std::getline() ensures that you capture all the user's input, including spaces, making it ideal for processing full lines of text in C++.

Input Streams

A detailed introduction to C++ Input Streams using std::cin and std::istringstream. Starting from the basics and progressing up to advanced use cases including creating collections of custom objects from our streams.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Handling Multiple Words with std::cin
How do I handle multiple words input with std::cin?
Use of peek() Method
What are the use cases of peek() in input streams?
Reading Multiple Objects from Stream
What is the best way to read multiple objects from a stream?
Using Custom Delimiters with std::getline()
How can I use std::getline() with a custom delimiter?
std::getline() vs get()
What is the difference between std::getline() and the get() method?
Creating Objects from Stream
How do I create a dynamic array of objects from stream data?
Third-Party Libraries for Input Streams
What third-party libraries simplify working with input streams?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant