C++ 读取和解析逗号分隔数据

来源:互联网 发布:大数据时代的财务核算 编辑:程序博客网 时间:2024/05/20 07:52

问题

在 C++ 中读取和解析逗号分隔的数据。

思路

使用 getline 和 stringstream 以 ',' 为分隔符来切分数据,然后使用标准库 string 的数值转换函数例如字符串转整形 stoi 进行解析。

代码

#include <iostream>#include <iomanip>#include <vector>#include <string>#include <sstream>using namespace std;int main() {    string raw_data("3, 4, 5, 76"), tmp;    vector<string> data;    stringstream input(raw_data);    while (getline(input, tmp, ',')) data.push_back(tmp);    for (auto s : data) cout << stoi(s) << endl;    return 0;}

输出:

34576

参考

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