65,187
社区成员




20.8 string 流
iostream库支持在string 对象上的内存操作ostringstream 类向一个string 插入字符
istringstream 类从一个string 对象读取字符而stringstream 类可以用来支持读和写两种操作
为了使用string 流字符串流我们必须包含相关的头文件
#include <sstream>
例如下面的函数把整个文件alice_emma 读到一个ostringstream 类对象buf 中buf 随
输入的字符而增长以便容纳所有的字符
#include <string>
#include <fstream>
#include <sstream>
string read_file_into_string()
{
ifstream ifile( "alice_emma" );
ostringstream buf;
char ch;
while ( buf && ifile.get( ch ))
buf.put( ch );
return buf.str();
}
成员函数str()返回与ostringstream 类对象相关联的string 对象我们可以用与处理普通
string 对象一样的方式来操纵这个string 对象例如在下面的程序中我们用与buf 关联
的string 对象按成员初始化text
int main()
{
string text = read_file_into_string();
// 标记出文本中每个换行符的位置
vector< string::size_type > lines_of_text;
string::size_type pos = 0;
while ( pos != string::npos )
{
pos = text.find( '\n', pos );
lines_of_text.push_back( pos );
}
// ...
}
ostringstream 对象也可以用来支持复合string 的自动格式化即由多种数据类型构成
的字符串例如输出操作符自动地将类型转换成相应的字符串表示而不用担心所需的存
储区大小
#include <iostream>
#include <sstream>
int main()
{
int ival = 1024; int *pival = &ival;
double dval = 3.14159; double *pdval = &dval;
ostringstream format_message;
// ok: 把值转换成 string 表示
format_message << "ival: " << ival
<< " ival's address: " << pival << '\n'
<< "dval: " << dval
<< " dval's address: " << pdval << endl;
string msg = format_message.str();
cout << " size of message string: " << msg.size()
<< " message: " << msg << endl;
}
在某些情况下把非致命的诊断错误和警告集中在一起而不是在遇到的地方显示出来
更受欢迎有一种简单的方法可以做到这一点就是提供一组一般形式的格式化重载函数
string
format( string msg, int expected, int received )
{
ostringstream message;
message << msg << " expected: " << expected
<< " received: " << received << "\n";
return message.str();
}
string format( string msg, vector<int> *values );
// ... 等等
于是应用程序可以存储这些字符串便于以后显示或许可以按严重程度进行分类
一般地它们可能会被分为Notify Log 或Error 类
istringstream 由一个string 对象构造而来它可以读取该string 对象istringstream 的一
种用法是将数值字符串转换成算术值例如
#include <iostream>
#include <sstream>
#include <string>
int main()
{
int ival = 1024; int *pival = &ival;
double dval = 3.14159; double *pdval = &dval;
// 创建一个字符串存储每个值并
// 用空格作为分割
format_string << ival << " " << pival << " "
<< dval << " " << pdval << endl;
// 提取出被存储起来的 ascii 值
// 把它们依次放在四个对象中
istringstream input_istring( format_string.str() );
input_istring >> ival >> pival
>> dval >> pdval;
}
stringstream out;
int x = 3;
long y = 4;
char z[5] = {0};
out << x << y << z << endl;
string str;
out>>str;
用ostringstream
// ostringstream::str
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main () {
ostringstream oss;
string mystr;
oss << "Sample string";
mystr=oss.str();
cout << mystr;
return 0;
}