到目前为止,所有的I / O你见过的例子已经向法庭写或读cin。然而,有一组类称为字符串,可以使用熟悉的插入流类(<<)和提取(>>)运营商使用字符串。像istream和ostream,字符串流提供一个缓冲区来保存数据。然而,不像CIN和法院,这些流不被连接到一个I / O通道(如键盘,显示器,等。)。一个字符串流的主要用途是缓冲输出显示在稍后的时间,或过程输入线。
有六类:字符串流对象(从istream),ostringstream之上(来自ostream),和stringstream(来自iostream)用于读写正常的字符宽度的字符串。wistringstream,wostringstream,和wstringstream用于读写宽字符字符串。使用stringstreams,你需要#包括sstream头头。
有两种方法得到的数据到河里:
stringstream os;
os << "en garde!" << endl; // insert "en garde!" into the stringstream
2) Use the str(string) function to set the value of the buffer:
stringstream os;
os.str("en garde!"); // set the stringstream buffer to "en garde!"
There are similarly two ways to get data out of a stringstream:
1) Use the str() function to retrieve the results of the buffer:
stringstream os;
os << "12345 67.89" << endl;
cout << os.str();