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.

相关推荐
无双@4 小时前
高并发内存池9 —— Page Cache 回收
c++·线程·秋招·项目·高并发内存池·c++项目·内存池
缺点内向4 小时前
Java: 为PDF批量添加图片水印实用指南
java·开发语言·pdf
西西学代码5 小时前
Flutter---异步编程
开发语言·前端·javascript
卡提西亚5 小时前
C++笔记-26-类模板
c++·笔记
song8546011345 小时前
锁的初步学习
开发语言·python·学习
重整旗鼓~5 小时前
38.附近商户实现
java·开发语言
沐怡旸5 小时前
【穿越Effective C++】条款19:设计class犹如设计type——用户定义类型的艺术与科学
c++·面试
一个不知名程序员www5 小时前
算法学习入门---模拟(C++)
c++·算法
夜月yeyue5 小时前
嵌入式开发中的 Git CI/CD
c++·git·单片机·嵌入式硬件·ci/cd·硬件架构
❀͜͡傀儡师5 小时前
JDK 25 新特性速览
java·开发语言