Skip to content

Instantly share code, notes, and snippets.

@gyillikci
Created November 19, 2023 08:58
Show Gist options
  • Save gyillikci/95c9d913457b768e94fe46be6456bd6c to your computer and use it in GitHub Desktop.
Save gyillikci/95c9d913457b768e94fe46be6456bd6c to your computer and use it in GitHub Desktop.
CSV Parse
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
// Function to parse CSV file
std::vector<std::vector<std::string>> parseCSV(const std::string& filename) {
std::vector<std::vector<std::string>> data;
// Open the CSV file
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Error opening file: " << filename << std::endl;
return data;
}
// Read and parse each line
std::string line;
while (std::getline(file, line)) {
std::vector<std::string> row;
std::stringstream ss(line);
std::string value;
while (std::getline(ss, value, ',')) {
row.push_back(value);
}
data.push_back(row);
}
// Close the file
file.close();
return data;
}
int main() {
// Replace "your_csv_file.csv" with the actual file name
std::string filename = "your_csv_file.csv";
// Parse the CSV file
std::vector<std::vector<std::string>> csvData = parseCSV(filename);
// Display the parsed data
for (const auto& row : csvData) {
for (const auto& value : row) {
std::cout << value << "\t";
}
std::cout << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment