乐闻世界logo
搜索文章和话题

How can I read and parse CSV files in C++?

1个答案

1

Reading and parsing CSV files in C++ typically involves the following steps:

  1. Open the file using file streams, such as std::ifstream.
  2. Read the file line by line and parse each line.
  3. Parse each line by splitting it using commas as delimiters to obtain individual fields.
  4. Store the parsed data in appropriate data structures, such as std::vector or std::map.
  5. Handle potential exceptions, such as file open failures or format errors.

Here is a concrete example demonstrating how to implement this process in C++:

cpp
#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> // Define a simple structure to store CSV data struct Person { std::string name; int age; std::string city; }; // Function to read and parse CSV files std::vector<Person> readCSV(const std::string& filename) { std::vector<Person> people; std::ifstream file(filename); // Check if the file is successfully opened if (!file.is_open()) { throw std::runtime_error("Cannot open file"); } std::string line; // Read each line of the file while (getline(file, line)) { std::istringstream s(line); std::string field; Person person; // Split each line using commas as delimiters getline(s, person.name, ','); getline(s, field, ','); person.age = std::stoi(field); // Convert string to integer getline(s, person.city, ','); // Add parsed data to the vector people.push_back(person); } file.close(); return people; } int main() { const std::string filename = "data.csv"; try { std::vector<Person> people = readCSV(filename); for (const Person& person : people) { std::cout << "Name: " << person.name << ", Age: " << person.age << ", City: " << person.city << std::endl; } } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; }

In this example:

  • We define a Person structure to store each CSV record.
  • Use std::ifstream to read the file and parse it line by line.
  • Use std::istringstream and getline to split strings.
  • Handle exceptions such as file open failures.

This approach is concise and clear, suitable for simple CSV parsing tasks. For files with complex CSV formats, such as those containing quotes or newlines, more sophisticated parsing strategies may be required, or you can use existing libraries like Boost Tokenizer.

2024年6月29日 12:07 回复

你的答案