主题
字符串流
#include <sstream> 提供三个字符串流类:std::istringstream(从字符串读)、std::ostringstream(向字符串写)、std::stringstream(读写皆可)。它们把一段内存里的字符串当成流来操作,让你对字符串也能用 <<、>>、getline 这些熟悉的接口。典型用途是格式化拼接和把字符串拆成数值/字段。
ostringstream:在内存里拼接格式化
std::ostringstream 像一个"只写不落盘"的 ofstream,你往里 << 各种类型,最后用 str() 取出完整字符串:
cpp
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::ostringstream buf;
std::string host = "db-01";
int port = 5432;
double load = 0.37;
// 把多种类型格式化拼到一起
buf << "host=" << host << " port=" << port << " load=" << load;
std::string msg = buf.str();
std::cout << msg << "\n";
// 比手动拼接字符串更省心:不用一个个 std::to_string
std::ostringstream alert;
alert << "端口 " << port << " 负载 " << load * 100 << "%";
std::cout << alert.str() << "\n";
return 0;
}str() 返回流内部累积的 std::string 副本。和直接拼 std::to_string 相比,字符串流的优势是格式控制一致——前面学的 std::setw、std::fixed、std::setprecision 都能用:
cpp
#include <iostream>
#include <sstream>
#include <iomanip>
int main()
{
std::ostringstream buf;
buf << std::fixed << std::setprecision(2);
buf << "圆周率 = " << 3.14159265;
std::cout << buf.str() << "\n"; // 圆周率 = 3.14
return 0;
}istringstream:把字符串拆成字段
std::istringstream 把一个字符串当作输入流,用 >> 按类型提取,是解析定长/分隔文本的利器:
cpp
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string record = "张三 28 92.5";
std::istringstream iss(record);
std::string name;
int age;
double score;
if (iss >> name >> age >> score) { // 一次性提取多个字段
std::cout << "姓名:" << name << "\n";
std::cout << "年龄:" << age << "\n";
std::cout << "分数:" << score << "\n";
}
return 0;
}>> 自动跳过空白、按目标类型转换,比手写 substr + atoi 干净得多。提取失败(类型不符)时流变假,可用 if (iss >> ...) 判断。
逐词拆分一段长文本也很方便:
cpp
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string paragraph = "知行合一 学而时习 温故知新";
std::istringstream words(paragraph);
std::string w;
while (words >> w) // 每次取一个词
std::cout << "-" << w << "\n";
return 0;
}stringstream:可读可写
std::stringstream 既能写又能读。常用于"先写入、再读取"的两阶段处理:
cpp
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::stringstream ss;
// 第一阶段:写入
int a = 7, b = 13;
ss << a << " " << b;
// 第二阶段:读取
int x, y;
ss >> x >> y;
std::cout << "x=" << x << " y=" << y << " sum=" << x + y << "\n";
return 0;
}注意写入后要读取时,流的位置已在末尾,需用 seekg(0) 回到开头或重新构造一个流。更稳妥的做法是写完后 ss.str() 取出字符串,再喂给新的 istringstream。
字符串与数值互转
字符串流是"万能转换器"——配合模板,可以写通用的数值↔字符串转换工具:
cpp
#include <iostream>
#include <sstream>
#include <string>
template<typename T>
std::string toStr(const T& v)
{
std::ostringstream os;
os << v;
return os.str();
}
template<typename T>
bool fromStr(const std::string& s, T& out)
{
std::istringstream is(s);
is >> out;
return static_cast<bool>(is); // 转换成功与否
}
int main()
{
std::cout << toStr(3.14) << "\n";
std::cout << toStr(42) << "\n";
int n;
if (fromStr("2024", n))
std::cout << "解析出整数 " << n << "\n";
double d;
if (fromStr("3.14abc", d)) // 读到 3.14 即停,剩余 "abc" 留在流里
std::cout << "解析出浮点 " << d << "\n";
int bad;
if (!fromStr("xyz", bad))
std::cout << "非数字,转换失败\n";
return 0;
}现代 C++ 也有 std::to_string / std::stoi 等专门函数,简单场景用它们更直接;但需要自定义格式(精度、进制)或处理复合类型时,字符串流仍是最灵活的选择。
解析结构化行
实际数据常是一行一条记录、字段间用分隔符。字符串流配合 getline 的三参重载(指定分隔符)很顺手:
cpp
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string line = "1001,鼠标,79.9,300"; // 编号,品名,单价,库存
std::istringstream row(line);
std::string id, name, priceStr, stockStr;
std::getline(row, id, ',');
std::getline(row, name, ',');
std::getline(row, priceStr, ',');
std::getline(row, stockStr);
std::cout << "编号:" << id << "\n"
<< "品名:" << name << "\n"
<< "单价:" << priceStr << "\n"
<< "库存:" << stockStr << "\n";
return 0;
}getline(stream, target, delim) 以 delim 为分隔切出一段。把字符串字段再用 istringstream 转成数值,就完成了"一行记录 → 结构化数据"的解析。
课后练习
- 格式化拼接:用
std::ostringstream把一个日期(年、月、月、日三个整数)拼成YYYY-MM-DD格式字符串,月份和日不足两位补零(提示:用setw+setfill('0'))。 - 拆解记录:给定一行
"姓名 年龄 分数",用std::istringstream一次性提取三个字段并打印。再故意构造一行含非数字的内容,观察>>失败时流的行为。 - CSV 解析:写一个程序,读入多行
"编号,品名,单价"格式的字符串,用getline三参版以逗号分隔,再把单价字符串转成double累加求总价。 - 通用转换器:仿照本节的
toStr/fromStr模板,写一个bool strTo(const std::string&, T&),分别用int、double、std::string测试。思考:为什么传入std::string时>>也能工作?