std::getline()
and get()
are both used for reading input, but they serve different purposes and are used in distinct scenarios.
std::getline()
std::getline()
is designed to read an entire line of input, including spaces, until it encounters a newline character (\n
) or a specified delimiter. It is typically used for reading strings:
#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
Input extracted: Hello World
In this example, std::getline()
captures the full input line, including spaces.
get()
The get()
method is a member function of input streams that reads one character at a time or into a buffer. It is more flexible but also more low-level compared to std::getline()
:
Here, get()
reads a single character from the stream:
#include <iostream>
#include <sstream>
int main() {
std::istringstream input{"Hello"};
char ch;
input.get(ch);
std::cout << "Character extracted: " << ch;
}
Character extracted: H
In this case, get()
reads up to three characters into the buffer (leaving space for the null terminator):
#include <iostream>
#include <sstream>
int main() {
std::istringstream input{"Hello"};
char buffer[4];
input.get(buffer, 4);
std::cout << "Buffer extracted: " << buffer;
}
Buffer extracted: Hel
std::getline()
is for reading entire lines, while get()
is for reading individual characters or fixed-size buffers.std::getline()
stops at a newline or a specified delimiter. get()
can use a delimiter but doesn’t move past it.get()
offers more control over reading characters, including using it to peek at characters without extracting them.std::getline()
is easier for handling user input and text processing. get()
is useful in scenarios requiring precise control over character extraction.Here’s a side-by-side example:
#include <iostream>
#include <sstream>
int main() {
std::string lineInput;
std::cout << "Enter a line: ";
std::getline(std::cin, lineInput);
std::cout << "Line extracted: "
<< lineInput << '\n';
std::istringstream input{"Hello"};
char charInput;
input.get(charInput);
std::cout << "Character extracted: "
<< charInput << '\n';
}
Enter a line: Hello World
Line extracted: Hello World
Character extracted: H
Choose std::getline()
for simplicity when working with lines and get()
for finer control over character-level input.
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.