温馨提示×

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

小樊
82
2024-09-03 15:29:23
栏目: 编程语言

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

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

  1. 将 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;
}
  1. 将 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 进行复杂数据格式的转换。你可以根据自己的需求修改这些示例,以处理其他类型的数据格式。

0