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.

相关推荐
blasit15 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_2 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛4 天前
delete又未完全delete
c++
端平入洛5 天前
auto有时不auto
c++
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1236 天前
matlab画图工具
开发语言·matlab
dustcell.6 天前
haproxy七层代理
java·开发语言·前端
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20216 天前
信号量和信号
linux·c++