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.