溫馨提示×

使用stringstream進行復雜數據格式轉換

小樊
93
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女