istringstream、ostringstream、stringstream 类介绍

本文介绍了C++中的istringstream、ostringstream和stringstream类,主要用于字符串的输入输出操作。特别是stringstream,它在处理string对象分割时非常有用。通过示例展示了如何利用stringstream分割string,并提醒了使用时注意默认的截断规则和如何处理特定分隔符的分割问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

istringstream、ostringstream、stringstream 类介绍

c++的输入输出主要分为以下3种

  1. 标准流输入输出(基于控制I/O)
头文件:#include <iostream>
		ostream:写到流中去
		istream:从流中读取
		iostream:对流进行读写
  1. 文件流输入输出(基于文件I/O)
头文件:#include <fstream>
		ifstream:从文件流中读取
		ofstream:写到文件流中
		fstream:对文件流进行读写
  1. 字符流输入输出(基于字符串I/O)
头文件:#include <sstream>
		istringstream:从字符串对象中读取
		ostringstream:写入到字符串对象中
		stringstream:对字符串对象进行读写
		

最近在做一道算法题目的时候,题目,遇到string对象的分割问题,故此重新学习以下stringstream便于以后查阅。stringstream主要用作string对象的分割,如下程序所示,利用stringstream分割string对象

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
	string str = "istringstream ostringstream stringstream";
	istringstream ss(str);
	string s;
	while (ss >> s)
	{
		cout << s << endl;
	}
	return 0;
}

/*
输出:
istringstream
ostringstream
stringstream
*/

需要注意的是,stringstream默认以空格,换行作为截断的地方,istringstream 是不能根据你指定的分隔符来切割字符串的,但是可以利用相关的技巧实现目标截断,如下:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
	string str = "110 ,   119   ,120";
	istringstream ss(str);
	int s;
	char c = ',';
	while (ss >> s >> c)
	{
		cout << s << endl;
	}
	return 0;
}
/*
输出:
110
119
*/
//注意不会输出120,因为后面没有,其中可以省掉标准的隔断的符号

对于字符串的特定符号分割,不建议这样做,这样做必须满足一定的条件,特定分隔符的左右必须要有空格分割,可以理解为这样,没有空格,也会把特定符号归结到字符串里面,所以必须加空格

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
	string str = "string,ame , fy ,";
	istringstream ss(str);
	string s;
	char c = ',';
	while (ss >> s >> c)
	{
		cout << s << endl;
	}
	return 0;
}

/*
输出:
string,ame
fy
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值