该CSV解析器能正确处理带引号字段、内部逗号、双引号转义及首尾空格;核心逻辑通过in_quotes状态机逐字符解析,跳过引号外的逗号,并将连续两个双引号替换为一个。

用C++写一个简单的CSV解析器,核心是按行读取、按逗号分隔字段,并正确处理带引号的字段(如"John, Doe"或"Text with ""double quotes""")。下面是一个轻量、可直接运行的实现,不依赖第三方库,支持常见CSV规则。
这个解析器能:
""表示一个")std::vector<:string></:string>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <cctype>
<p>std::vector<std::string> parse_csv_line(const std::string& line) {
std::vector<std::string> fields;
std::string field;
bool in_quotes = false;</p><pre class="brush:php;toolbar:false;">for (size_t i = 0; i < line.length(); ++i) {
char c = line[i];
if (c == '"') {
in_quotes = !in_quotes;
} else if (c == ',' && !in_quotes) {
// 字段结束
fields.push_back(field);
field.clear();
} else if (c == '\r' || c == '\n') {
// 忽略行内换行(实际CSV中少见,但容错)
continue;
} else {
// 普通字符:若在引号内且下一个是",则只加一个"
if (c == '"' && i + 1 < line.length() && line[i + 1] == '"') {
field += '"';
++i; // 跳过下一个"
} else {
field += c;
}
}
}
fields.push_back(field); // 最后一个字段
return fields;}
// 可选:去掉字段首尾空格 std::string trim(const std::string& s) { size_t start = s.find_first_not_of(" \t\r\n"); size_t end = s.find_last_not_of(" \t\r\n"); return (start == std::string::npos) ? "" : s.substr(start, end - start + 1); }
int main() { std::ifstream file("data.csv"); if (!file.is_open()) { std::cerr
std::string line;
while (std::getline(file, line)) {
auto fields = parse_csv_line(line);
// 去空格(可选)
for (auto& f : fields) f = trim(f);
// 打印结果(调试用)
std::cout << "行: [";
for (size_t i = 0; i < fields.size(); ++i) {
std::cout << "\"" << fields[i] << "\"";
if (i < fields.size() - 1) std::cout << ", ";
}
std::cout << "]\n";
}
return 0;}
把下面内容保存为data.csv,运行程序即可验证:
立即学习“C++免费学习笔记(深入)”;
Name,Age,City "Smith, John",28,"New York" "Alice ""The Great""",31,"San Francisco" Bob,25,Chicago
输出会是:
行: ["Name", "Age", "City"] 行: ["Smith, John", "28", "New York"] 行: ["Alice \"The Great\"", "31", "San Francisco"] 行: ["Bob", "25", "Chicago"]
这个版本适合学习和中小规模数据。真实项目中要注意:
getline
parse_csv_line之后增加类型推导逻辑基本上就这些——不复杂但容易忽略引号转义和状态切换。动手改一改,就能适配你的具体需求。
以上就是C++如何实现一个简单的CSV文件解析器?(代码示例)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号