使用stringstream进行复杂数据格式转换

   2024-09-30 5820
核心提示:stringstream 是 C++ 标准库中的一个类,它允许你在内存中读写字符串。你可以使用 stringstream 来解析和生成复杂的数据格式,例

stringstream 是 C++ 标准库中的一个类,它允许你在内存中读写字符串。你可以使用 stringstream 来解析和生成复杂的数据格式,例如将 JSON 字符串转换为 C++ 对象,或将 CSV 数据转换为二维数组等。

下面是一个简单的示例,展示了如何使用 stringstream 进行复杂数据格式的转换:

将 JSON 字符串转换为 C++ 对象:
#include <iostream>#include <sstream>#include <string>#include <nlohmann/json.hpp>using json = nlohmann::json;using namespace std;int main() {    string json_str = R"(    {        "name": "John",        "age": 30,        "city": "New York"    })";    stringstream ss(json_str);    json j;    ss >> j;    cout << "Name: " << j["name"] << endl;    cout << "Age: " << j["age"] << endl;    cout << "City: " << j["city"] << endl;    return 0;}
将 CSV 数据转换为二维数组:
#include <iostream>#include <sstream>#include <string>#include <vector>using namespace std;vector<vector<int>> parse_csv(const string& csv_str) {    vector<vector<int>> data;    stringstream ss(csv_str);    string row_str;    while (getline(ss, row_str, ',')) {        vector<int> row;        stringstream row_ss(row_str);        string cell_str;        while (getline(row_ss, cell_str, ' ')) {            row.push_back(stoi(cell_str));        }        data.push_back(row);    }    return data;}int main() {    string csv_str = R"(    1,2,3    4,5,6    7,8,9    )";    vector<vector<int>> data = parse_csv(csv_str);    for (const auto& row : data) {        for (int num : row) {            cout << num << " ";        }        cout << endl;    }    return 0;}

这些示例展示了如何使用 stringstream 进行复杂数据格式的转换。你可以根据自己的需求修改这些示例,以处理其他类型的数据格式。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号