Yes, you can use string streams to parse comma-separated values (CSV) in C++. String streams (std::istringstream
) are particularly useful for breaking down a CSV line into individual values.
Here’s a basic example to parse a single line of CSV:
#include <iostream>
#include <sstream>
#include <vector>
std::vector<std::string> ParseCSVLine(
const std::string& line
) {
std::vector<std::string> result;
std::istringstream Stream(line);
std::string value;
while (std::getline(Stream, value, ',')) {
result.push_back(value);
}
return result;
}
int main() {
std::string line = "name,age,city";
std::vector<std::string> values =
ParseCSVLine(line);
for (const auto& value : values) {
std::cout << value << "\n";
}
}
name
age
city
In this example, std::getline()
reads from the stream until it encounters a comma, extracting each value into the value
variable. These values are then stored in a std::vector
.
To parse multiple lines of CSV data, you can read each line from the input and process it using the ParseCSVLine
 function:
#include <iostream>
#include <sstream>
#include <vector>
using CSVLine = std::vector<std::string>;
using CSVFile = std::vector<CSVLine>;
CSVLine ParseCSVLine(const std::string&) {/*...*/}
CSVFile ParseCSV(
const std::string& data) {
CSVFile result;
std::istringstream Stream(data);
std::string line;
while (std::getline(Stream, line)) {
result.push_back(ParseCSVLine(line));
}
return result;
}
int main() {
std::string data =
"name,age,city\nAlice,30,New York\n"
"Bob,25,Los Angeles";
CSVFile rows =
ParseCSV(data);
for (const auto& row : rows) {
for (const auto& value : row) {
std::cout << value << " ";
}
std::cout << "\n";
}
}
name age city
Alice 30 New York
Bob 25 Los Angeles
When parsing CSV data, you may encounter cases where values contain commas or are enclosed in quotes. Handling these edge cases requires additional parsing logic. For simplicity, here’s a basic approach without handling quoted values:
CSVLine ParseCSVLine(const std::string& line) {
std::vector<std::string> result;
std::istringstream Stream(line);
std::string value;
while (std::getline(Stream, value, ',')) {
// Trim spaces from value
value.erase(0, value.find_first_not_of(' '));
value.erase(value.find_last_not_of(' ') + 1);
result.push_back(value);
}
return result;
}
std::getline()
with a string stream to parse CSV lines.Using string streams for parsing CSV is a powerful technique for simple and complex data processing tasks.
Answers to questions are automatically generated and may not have been reviewed.
A detailed guide to C++ String Streams using std::stringstream
. Covers basic use cases, stream position seeking, and open modes.