Loading

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 @ 2022-10-26 22:37  二次元攻城狮  阅读(106)  评论(0编辑  收藏  举报