C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++ string流

C++中string流的具体使用

作者:点云SLAM

本文主要介绍了C++中string流的具体使用,包括istringstream、ostringstream、stringstream这三种类型的使用,具有一定的参考价值,感兴趣的可以了解一下

一、概览与类体系

C++ 提供三种基于内存字符串的流,定义在 <sstream> 中:

它们都继承自 std::basic_iostream<char>,可使用所有流操作符与格式化工具。

二、常见用法

1. 构造与取出字符串

std::ostringstream oss;             // 默认空缓冲
oss << "Value=" << 42 << ", Pi=" 
    << std::fixed << std::setprecision(3) << 3.14159;
// 获取结果
std::string s = oss.str();          // s == "Value=42, Pi=3.142"

2. 字符串解析

std::string line = "123  45.6 OK";
// 将 line 内容作为流缓冲
std::istringstream iss(line);

int    a;
double b;
std::string status;

// 按空白自动切分并转换
if (iss >> a >> b >> status) {
    // a==123, b==45.6, status=="OK"
}

// 检查是否完全消费或错误
if (iss.fail() && !iss.eof()) {
    // 转换中发生格式错误
}

3. 读写混合

std::stringstream ss;
ss << "X=" << 10 << ";Y=" << 20;
// 重设读写位置到开头
ss.seekg(0);

// 逐字符读取、跳过标识
char    ch;
int     x, y;
ss >> ch >> ch >> x;   // 假设格式 "X=10"
ss >> ch >> ch >> y;   // 跳过 ";Y="

三、格式控制与状态检查

格式化:与标准流一致,可用 <iomanip> 中的操纵器,如 std::hex、std::setw、std::setfill、std::boolalpha、std::fixed、std::scientific 等调整输出格式。

状态位:用 good()、fail()、eof()、bad()、rdstate() 检测流状态;用 clear() 重置。

异常模式

iss.exceptions(std::ios::failbit | std::ios::badbit);
try {
  int v; 
  iss >> v;  // 解析失败即抛异常
} catch (const std::ios_base::failure& e) {
  // 处理错误
}

默认不会抛。

四、性能与注意事项

五、综合示例

#include <iostream>
#include <sstream>
#include <iomanip>

int main() {
    // 构建字符串
    std::ostringstream oss;
    oss << "Point(" 
        << std::setw(2) << std::setfill('0')
        << 7 << "," 
        << std::fixed << std::setprecision(1)
        << 3.14 << ")";
    std::string desc = oss.str();  // "Point(07,3.1)"
    std::cout << desc << "\n";

    // 解析回数值
    std::istringstream iss(desc);
    char ch;
    int ix;
    double dy;
    if ( (iss >> ch >> ch >> ix >> ch >> dy >> ch).good() ) {
        std::cout << "Parsed: x=" << ix << ", y=" << dy << "\n";
    } else {
        std::cerr << "Parse error\n";
    }

    // 读写混合:累加偏移
    std::stringstream ss("100 200 300");
    int sum = 0, v;
    while (ss >> v) sum += v;  // sum=600
    std::cout << "Sum=" << sum << "\n";

    return 0;
}

小结

掌握这些知识,你就能在日志构建、文本解析、动态内容生成等场景中,灵活高效地运用 C++ 的字符串流。

到此这篇关于C++中string流的具体使用的文章就介绍到这了,更多相关C++ string流内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文