码迷,mamicode.com
首页 > 其他好文 > 详细

字符串流 istringstream 和 ostringstream 的用法

时间:2015-03-29 18:05:14      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

stringstream  特定的操作

stringstream strm; // 创建自由的 stringstream 对象
stringstream strm(s); //创建存储 s 的副本的 stringstream 对象,其中 s 是 string 类型的对象
strm.str()  //返回 strm 中存储的 string 类型对象
strm.str(s)  //将 string 类型的 s 复制给 strm,返回 void 

 stringstream  对象的和使用 
前面已经见过以每次一个单词或每次一行的方式处理输入的程序。第一种程
序用 string 输入操作符,而第二种则使用 getline 函数。然而,有些程序需
要同时使用这两种方式:有些处理基于每行实现,而其他处理则要操纵每行中每
个单词。可用 stringstreams 对象实现:

string line, word;      // will hold a line and word from input,respectively
while (getline(cin, line))
{
    // read a line from theinput into line do per-line processing
    istringstream stream(line);  // bind to stream to the
    line we read
    while (stream >> word)
    { 
         // read a word from line
         // do per-word processing
    }
}

这里,使用 getline 函数从输入读取整行内容。然后为了获得每行中的单词,将一个 istringstream 对象与所读取的行绑定起来,这样只需要使用普通的 string 输入操作符即可读出每行中的单词。

stringstream  提供的转换和/或格式化 
stringstream 对象的一个常见用法是,需要在多种数据类型之间实现自动格式化时使用该类类型。例如,有一个数值型数据集合,要获取它们的 string 表示形式,或反之。sstream 输入和输出操作可自动地把算术类型转化为相应的 string 表示形式,反过来也可以。

int val1 = 512, val2 = 1024;
ostringstream format_message;
// ok: converts values to a string representation
format_message << "val1: " << val1 << "\n"<< "val2: " << val2 << "\n"; 

这里创建了一个名为 format_message 的 ostringstream 类型空对象,并将指定的内容插入该对象。重点在于 int 型值自动转换为等价的可打印的字符串。format_message 的内容是以下字符:

val1: 512\nval2: 1024 

相反,用 istringstream 读 string 对象,即可重新将数值型数据找回来。读取 istringstream 对象自动地将数值型数据的字符表示方式转换为相应的算术值。

// str member obtains the string associated with a stringstream
istringstream input_istring(format_message.str());
string dump; // place to dump the labels from the formatted message
// extracts the stored ascii values, converting back to arithmetic types
input_istring >> dump >> val1 >> dump >> val2;
cout << val1 << " " << val2 << endl;  // prints 512 1024 

这里使用 。str 成员获取与之前创建的 ostringstream 对象关联的 string 副本。再将 input_istring 与 string 绑定起来。在读 input_istring 时,相应的值恢复为它们原来的数值型表示形式为了读取 input_string,必须把该 string 对象分解为若干个部分。我们要的是数值型数据;为了得到它们,必须读取(和忽略)处于所需数据周围的标号。

因为输入操作符读取的是有类型的值,因此读入的对象类型必须和由 stringstream 读入的值的类型一致。在本例中,input_istring 分成四个部分:
string 类型的值 val1,接着是 512,然后是 string 类型的值 val2,最后是 1024。一般情况下,使用输入操作符读 string 时,空白符将会忽略。于是,在读与 format_message 关联的 string 时,忽略其中的换行符。

字符串流 istringstream 和 ostringstream 的用法

标签:

原文地址:http://blog.csdn.net/xum2008/article/details/44728499

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!