阅读量:126
stringstream 是 C++ 标准库中的一个类,它允许你在内存中读写字符串。你可以使用 stringstream 来解析和生成复杂的数据格式,例如将 JSON 字符串转换为 C++ 对象,或将 CSV 数据转换为二维数组等。
下面是一个简单的示例,展示了如何使用 stringstream 进行复杂数据格式的转换:
- 将 JSON 字符串转换为 C++ 对象:
#include
#include
#include
#include
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 class="hljs-string">"name"] << endl class="hljs-string">"Age: " << j class="hljs-string">"age"] << endl class="hljs-string">"City: " << j class="hljs-string">"city"] << endl class="hljs-keyword">return 0;
}
- 将 CSV 数据转换为二维数组:
#include
#include
#include
#include
using namespace std;
vectorint>> parse_csv(const string& csv_str) {
vectorint>> 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
)";
vectorint>> data = parse_csv(csv_str);
for (const auto& row : data) {
for (int num : row) {
cout << num class="hljs-string">" ";
}
cout << endl class="hljs-keyword">return 0;
}
这些示例展示了如何使用 stringstream 进行复杂数据格式的转换。你可以根据自己的需求修改这些示例,以处理其他类型的数据格式。