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.
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.
std::getline()
>>
operatorUsing std::getline()
ensures that you capture all the user's input, including spaces, making it ideal for processing full lines of text in C++.
Answers to questions are automatically generated and may not have been reviewed.
A detailed introduction to C++ Input Streams using std::cin
and istringstream
. Starting from the basics and progressing up to advanced use cases including creating collections of custom objects from our streams.
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.
View Course