ostringstream和istringstream的问题

大狮兄 2014-01-05 01:56:44
这两个东西,用法我基本了解了,但是存在的意义是什么呢?都是读取一个string对象,直接使用string对象就行了啊,为什么还要多此一举来个ostringstream和istringstream中转站呢?
...全文
252 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
飞天御剑流 2014-01-05
  • 打赏
  • 举报
回复
引用 6 楼 lg1544650023 的回复:
举个简单的例子,怎样把一个字符串中的每个单词保留到一个vector中 比如把这句话放入一个vector:Hear from your industry peers and share your experiences at Oracle Industry Connect. 用sstream就会很方便:
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
	string str = "Hear from your industry peers and share your experiences at Oracle Industry Connect";
	vector<string> words;
	istringstream iss(str);
	string word;
	while (iss >> word)
	{
		words.push_back(word);
	}
	cout << "words in vector :" << endl;
	for (string word : words)
	{
		cout << word << endl;
	}
	return 0;
}
你搞复杂了,如下就行了:

string str = "Hear from your industry peers and share your experiences at Oracle Industry Connect";
vector<string> words;
istringstream iss(str);
copy( istream_iterator< string >( iss ), istream_iterator< string >(), back_inserter( words ) );
sleeplacker 2014-01-05
  • 打赏
  • 举报
回复
举个简单的例子,怎样把一个字符串中的每个单词保留到一个vector中 比如把这句话放入一个vector:Hear from your industry peers and share your experiences at Oracle Industry Connect. 用sstream就会很方便:
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
	string str = "Hear from your industry peers and share your experiences at Oracle Industry Connect";
	vector<string> words;
	istringstream iss(str);
	string word;
	while (iss >> word)
	{
		words.push_back(word);
	}
	cout << "words in vector :" << endl;
	for (string word : words)
	{
		cout << word << endl;
	}
	return 0;
}
mujiok2003 2014-01-05
  • 打赏
  • 举报
回复
引用
都是读取一个string对象
支持string的读写,但远不止这些.
AndyStevens 2014-01-05
  • 打赏
  • 举报
回复
有点UNIX文化的意思
大狮兄 2014-01-05
  • 打赏
  • 举报
回复
引用 1 楼 supermegaboy 的回复:
iostringstream是流,string是字符串,两者不同的东西,iostringstream可以像其它流一样使用<<和>>格式化输出输入,这才是iostringstream的用处,string行吗?iostringstream相当于C中的sscanf和sprintf,你说sscanf和sprintf能去掉吗?
哦哦,我对流的印象不是很深,等下再回过去复习下。
max_min_ 2014-01-05
  • 打赏
  • 举报
回复
流的概念的, 楼上解释的很透彻了!
飞天御剑流 2014-01-05
  • 打赏
  • 举报
回复
iostringstream是流,string是字符串,两者不同的东西,iostringstream可以像其它流一样使用<<和>>格式化输出输入,这才是iostringstream的用处,string行吗?iostringstream相当于C中的sscanf和sprintf,你说sscanf和sprintf能去掉吗?

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧