C++

关于stringstream的str方法

2011/2/27

关于基础的stringstream使用参照 http://www.singmelody.com/?p=459

stringstream的str方法:

官方解释:

http://www.cplusplus.com/reference/iostream/stringstream/str/

string str ( ) const;

void str ( const string & s );

Get/set the associated string object

The first version returns a copy of the string object currently associated with the string stream buffer.

The second syntax copies the content of string s to the string object associated with the string stream buffer.

The function effectivelly calls rdbuf()->str().

Notice that setting a new string does not clear the error flags currently set in the stream object unless the member function clear is explicitly called.

Parameters

s

String object whose content is to be copied to the string stream buffer.

Return Value

The first version returns a copy of the string object currently associated with the stream buffer.

Example

// stringstream::str
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main () {

  stringstream oss;
  string mystr;

  oss << "Sample string";
  mystr=oss.str();

  cout << mystr;

  return 0;
}

自己的小例子:

// stringstream::str
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main () {

  stringstream oss;
  string mystr;
  string secondmystr;

  oss << "Sample string";
  mystr=oss.str();

  oss>>secondmystr;

  cout<<mystr<<endl;	//echo "Sample string"

  cout<<secondmystr<<endl;	//just "Sample"
  return 0;
}