C++标准库字符串流sstream

sstream与strstream#

在C++有两种字符串流,一种在<strstream>中定义,另一种在<sstream>中定义,两者的区别如下:

  • strstream里包含strstreambuf、istrstream、ostrstream、strstream,是基于C类型字符串char*编写的,如ostrstream::str()返回的是char*类型的字符串
  • sstream里包含stringbuf、istringstream、ostringstream、stringstream,是基于std::string编写的,如ostringstream::str()返回的是std::string类型的字符串

<strstream>中的类已经不推荐使用(deprecated in C++98)任何时候都应当使用<sstream>而不是<strstream>。

ostringstream#

ostringstream用来进行格式化的输出,可以将各种类型转换为string类型,只支持 << 操作符

//这个字符串流只能使用 << 操作符
ostringstream ostrs;   
ostrs << 3.14 << " ";
ostrs << "ab" << ",";
cout << ostrs.str();    
//输出 3.14 ab,

istringstream#

istringstream用于把字符串中以空格隔开的内容提取出来,只支持 >> 操作符

string str1,str2;
string instr = "1 2 3 4 5 6 7";
// 通过构造函数赋值
istringstream iss(instr);	
while (iss >> str1 >> str2)
{
	cout << str1 << " " << str2 << endl;
}
//输出
//1 2
//3 4
//5 6

stringstream#

stringstream是ostringstream和istringstream的综合,支持 < 和 >> 操作

int num; string str1,str2;
string input = "1 2 3 4 5 6 7";
stringstream ss;
ss << input;
while (ss >> num >> str1 >> str2) 
{
    cout << num << " " << str1 << " " << str2 << endl;
}
//输出
//1 2 3
//4 5 6

//用str()转换成string类型才能输出
cout << ss.str() << endl;

//字符串清空
ss.str("");
posted @   二次元攻城狮  阅读(139)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
  1. 1 烟花易冷 小柔Channel
  2. 2 红颜如霜 江壹纯
  3. 3 不谓侠 小桃Channel
  4. 4 小小恋歌 新坦结衣
  5. 5 神预言 袁娅维TIARAY
小小恋歌 - 新坦结衣
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.
点击右上角即可分享
微信分享提示
主题色彩