Using std::getline()
with a custom delimiter is straightforward and allows you to read input up to the specified character. This is useful when dealing with structured data formats where different delimiters are used.
By default, std::getline()
reads input until a newline character is encountered. You can provide a custom delimiter as the 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()
uses a comma as the delimiter, extracting substrings separated by commas.
For more complex delimiters or multi-character separators, you might need to manually parse the input. However, for single-character delimiters, std::getline()
is very effective.
Consider a scenario where data entries are separated by a semicolon:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main() {
std::string input = "Legolas;Gimli;Aragorn";
std::istringstream stream(input);
std::string name;
std::vector<std::string> names;
while (std::getline(stream, name, ';')) {
names.push_back(name);
}
for (const auto& n : names) {
std::cout << "Name: " << n << '\n';
}
}
Name: Legolas
Name: Gimli
Name: Aragorn
In this example, std::getline()
reads the names separated by semicolons and stores them in a vector.
Always check the stream state after reading to handle any potential errors or unexpected input. Using a loop with std::getline()
ensures robust error handling.
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string input = "Legolas;Gimli;Aragorn";
std::istringstream stream(input);
std::string name;
while (std::getline(stream, name, ';')) {
if (name.empty()) {
std::cerr << "Empty entry found\n";
} else {
std::cout << "Name: " << name << '\n';
}
}
}
Name: Legolas
Name: Gimli
Name: Aragorn
Using custom delimiters with std::getline()
provides a powerful tool for reading and processing structured input, making it versatile for various applications 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.