C++ 基于字符串的IO操作、字符串转换

stringstream 是 C++ 标准库中的一个非常有用的类,它允许你像操作输入/输出流一样操作字符串。它是 <sstream> 头文件中定义的类,结合了字符串和流的特性。

std::stringstream   //用于读写字符串
std::istringstream  //只用于从字符串读取
std::ostringstream  //只用于向字符串写入

基本用法

#include <iostream>
#include <sstream>  //包含头文件
#include <string>
using namespace std;

int main() {
	stringstream ss;  //创建对象

	ss << "Hello" << " " << "World!" << " " << "2025"; //往ss写入数据

	string content = ss.str(); //获取字符串内容

	cout << "content: " << content << endl;

	string p1, p2;
	int year;

	ss >> p1 >> p2 >> year; //从ss中读取数据
	
	cout << "p1: " << p1 << endl << "p2: " << p2 
		<< endl << "year: " << year << endl;

	return 0;
}

实际应用案例

(1)字符串拼接
std::stringstream ss;
ss << "The answer is: " << 42;
std::string result = ss.str(); // "The answer is: 42"

也可以用 +、+=、string类中的append方法,等等。

虽然stringstream 通常比直接字符串拼接效率低,但在需要复杂格式化时非常有用。

(2)字符串分割
std::string data = "John,Doe,30";
std::stringstream ss(data);
std::string token;

while (std::getline(ss, token, ',')) {
    std::cout << token << std::endl;
}
// 输出:
// John
// Doe
// 30
(3)类型转换
std::string numStr = "123.45";
std::stringstream ss(numStr);
double num;
ss >> num; // 将字符串转换为double

但是一般使用C++11引入的std::to_string函数(包含string头文件)更加方便:

int i = 42;
std::string s = std::to_string(i);  // "42"

double d = 3.14;
std::string s2 = std::to_string(d); // "3.140000"

float f = 2.5f;
std::string s3 = std::to_string(f); // "2.500000"

此外,还有反向转换(字符串转数值)

std::stoi()   //转 int
std::stol()   //转 long
std::stoll()  //转 long long
std::stoul()  //转 unsigned long
std::stoull() //转 unsigned long long
std::stof()   //转 float
std::stod()   //转 double
std::stold()  //转 long double

stringstream重要成员函数介绍

(1)str() :获取或设置字符串内容
std::string content = ss.str(); // 获取
ss.str("New content"); // 设置
(2)clear() :清除错误状态标志
ss.clear(); // 清除可能出现的错误状态

重复使用同一个 stringstream 对象时,最好先调用 clear() 清除状态,然后调用 str("") 清空内容。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值