跳转到内容

C++ 字符串流

来自代码酷

C++字符串流(String Streams)是C++标准库中提供的一种特殊类型的流,用于将内存中的字符串像文件流一样进行读写操作。它们属于<sstream>头文件,主要包括以下三个类:

  • std::istringstream(输入字符串流)
  • std::ostringstream(输出字符串流)
  • std::stringstream(双向字符串流)

字符串流常用于字符串与其他数据类型(如整数、浮点数)之间的高效转换,或复杂字符串的格式化拼接。

核心类与用途[编辑 | 编辑源代码]

以下表格总结了字符串流的主要类及其功能:

类名 描述 典型用途
istringstream 从字符串读取数据 解析字符串中的数字或单词
ostringstream 向字符串写入数据 格式化拼接字符串
stringstream 双向读写字符串 混合输入输出操作

基本用法示例[编辑 | 编辑源代码]

字符串到数值的转换(istringstream[编辑 | 编辑源代码]

以下代码演示如何从字符串中提取整数和浮点数:

  
#include <iostream>  
#include <sstream>  
#include <string>  

int main() {  
    std::string data = "42 3.14 hello";  
    std::istringstream iss(data);  

    int num;  
    float pi;  
    std::string text;  

    iss >> num >> pi >> text;  // 按顺序提取数据  

    std::cout << "整数: " << num << "\n"  
              << "浮点数: " << pi << "\n"  
              << "字符串: " << text << std::endl;  
    return 0;  
}

输出

  
整数: 42  
浮点数: 3.14  
字符串: hello  

数值到字符串的转换(ostringstream[编辑 | 编辑源代码]

使用输出流将多个变量拼接为一个字符串:

  
#include <sstream>  
#include <iostream>  

int main() {  
    std::ostringstream oss;  
    int x = 10;  
    double y = 2.5;  

    oss << "x=" << x << ", y=" << y;  // 格式化写入  
    std::string result = oss.str();   // 获取结果字符串  

    std::cout << result << std::endl; // 输出: x=10, y=2.5  
    return 0;  
}

高级应用场景[编辑 | 编辑源代码]

数据清洗与解析[编辑 | 编辑源代码]

假设有一个CSV格式的字符串,需提取每行的字段:

  
#include <sstream>  
#include <vector>  

std::vector<std::string> parseCSVLine(const std::string& line) {  
    std::vector<std::string> fields;  
    std::istringstream iss(line);  
    std::string field;  

    while (std::getline(iss, field, ',')) {  // 按逗号分隔  
        fields.push_back(field);  
    }  
    return fields;  
}

动态SQL查询生成[编辑 | 编辑源代码]

通过ostringstream安全拼接SQL条件:

  
std::string buildQuery(const std::string& table, const std::map<std::string, std::string>& conditions) {  
    std::ostringstream oss;  
    oss << "SELECT * FROM " << table << " WHERE ";  

    for (auto it = conditions.begin(); it != conditions.end(); ++it) {  
        if (it != conditions.begin()) oss << " AND ";  
        oss << it->first << " = '" << it->second << "'";  
    }  
    return oss.str();  
}

性能与注意事项[编辑 | 编辑源代码]

  • 内存管理:字符串流会动态分配内存,频繁创建/销毁可能影响性能。
  • 错误处理:使用fail()检查提取是否成功:
  
  if (!(iss >> value)) {  
      std::cerr << "解析失败!" << std::endl;  
  }

总结[编辑 | 编辑源代码]

C++字符串流提供了灵活的字符串处理能力,尤其适合以下场景:

  • 数据类型转换(字符串 ↔ 数值)
  • 复杂字符串的格式化生成
  • 结构化文本解析

通过合理使用istringstreamostringstreamstringstream,可以简化代码并提高可读性。