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.

相关推荐
Never_Satisfied15 分钟前
C#获取汉字拼音字母方法总结
开发语言·c#
zh_xuan28 分钟前
kotlin 密封类
开发语言·kotlin
码小猿的CPP工坊37 分钟前
C++软件开发之内存泄漏闭坑方法
开发语言·c++
Ethan-D39 分钟前
#每日一题19 回溯 + 全排列思想
java·开发语言·python·算法·leetcode
Benny_Tang39 分钟前
题解:CF2164C Dungeon
c++·算法
满栀5851 小时前
分页插件制作
开发语言·前端·javascript·jquery
froginwe111 小时前
C 标准库 - <stdio.h>
开发语言
zwtahql1 小时前
php源码级别调试
开发语言·php
qq_406176141 小时前
深入剖析JavaScript原型与原型链:从底层机制到实战应用
开发语言·前端·javascript·原型模式
青小莫2 小时前
C语言vsC++中的动态内存管理(内含底层实现讲解!)
java·c语言·c++