c++ stringstream字符串流的用法

stringstream为字符串流,既能输入也能输出。 能简化字符串的一些操作。测试代码:

cpp 复制代码
void testStringStream(void) {
	// 字符串转整型(可以转多个整型)
	std::string str = "9527 666 888";
	std::stringstream ss1(str); // 字符串流,支持双向操作
	int num1, num2, num3;
	ss1 >> num1 >> num2 >> num3; // 提取
	std::cout << "字符串转整型: " << "num1: " << num1 << ", num2: " << num2 << ", num3: " << num3 << std::endl;

	// 数字转字符串
	std::stringstream ss2;
	ss2 << 1314 << 520; // 插入
	std::string str2 = ss2.str();
	std::cout << "str2: " << str2 << std::endl; // 打印str2: 1314520

	// 字符串按空格分割
	std::string str3 = "i love u vicky du !";
	std::stringstream ss3(str3);
	std::string w;
	for (;ss3 >> w;) {
		std::cout << w << std::endl;
	}

	// 字符串自定义符号分割
	std::stringstream ss4("大师兄躺在何金银的怀里;等插到你了再说嘛,自然有法律制裁他");
	std::string s;
	for (;std::getline(ss4, s, ';');) {
		std::cout << s << std::endl;
	}

	// fail函数检查是否提取成功
	std::stringstream ss5("1314 520 爱你一万年 1314520");
	int a = 0;
	for (;;) { // 循环提取到1314、 520
		ss5 >> a;
		if (ss5.fail()) break;
		std::cout << a << std::endl;
	}

	// 可以清空后复用
	ss5.str("");
	ss5.clear();
	// ...
}

打印:

ok.

相关推荐
爱装代码的小瓶子5 分钟前
【C++与Linux基础】进程间通讯方式:匿名管道
android·c++·后端
CoderCodingNo5 分钟前
【GESP】C++ 二级真题解析,[2025年12月]第一题环保能量球
开发语言·c++·算法
独好紫罗兰9 分钟前
对python的再认识-基于数据结构进行-a005-元组-CRUD
开发语言·数据结构·python
LYOBOYI12311 分钟前
qtcpSocket详解
c++·qt
REDcker14 分钟前
gRPC完整文档
服务器·网络·c++·网络协议·grpc
chilavert31821 分钟前
技术演进中的开发沉思-356:重排序(中)
java·开发语言
devmoon24 分钟前
为 Pallet 搭建最小化 Mock Runtime 并编写单元测试环境
开发语言·单元测试·区块链·智能合约·polkadot
Coder_Boy_39 分钟前
Java开发者破局指南:跳出内卷,借AI赋能,搭建系统化知识体系
java·开发语言·人工智能·spring boot·后端·spring
Mr_Xuhhh44 分钟前
介绍一下ref
开发语言·c++·算法
王老师青少年编程1 小时前
2024年信奥赛C++提高组csp-s初赛真题及答案解析(完善程序第2题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组