9人参与 • 2025-06-11 • C/C++
c++ 提供三种基于内存字符串的流,定义在 <sstream> 中:
它们都继承自 std::basic_iostream<char>
,可使用所有流操作符与格式化工具。
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"
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()) { // 转换中发生格式错误 }
failbit
,后续操作将不中断程序,除非打开异常模式。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) { // 处理错误 }
默认不会抛。
str()
都会拷贝缓冲区字符串,影响性能。可在最后一次取用时再调用。ss.str().reserve(n)
或先构造带初始字符串的 stringstream
,减少动态分配。std::hex
),它会一直生效, remember to reset(std::dec
)。>>
默认以空白分隔,解析整行或含空格的字段时要用 std::getline
。std::basic_stringstream<wchar_t>
。#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流内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论