开发者

How can I copy value from ostringstream to string?

I tried :

ostringstream oss;
read a string from file and put to oss;
string str;
str << oss.str();// error here "error: no match for ‘operator>>’ in 'oss >> str' "

If I use str = oss.str(); Instead of printing t开发者_如何学Che value of the string, it prints out "....0xbfad75c40xbfad75c40xbf...." likes memory address.

Can anybody tell me why? Thank you.


string str = oss.str(); // this should do the trick


If you're trying to copy the whole file to a stringstream, then this:

oss << ifs;

is wrong. All that does is prints the address of ifs. What you want to do is this:

oss << ifs.rdbuf();

And then of course, to copy that to a string, like the others are saying:

str = oss.str();

If you just want to get a single line, then skip the stringstream, and just use getline:

std::getline(ifs,str);


<< is an operator defined on streams, which a string is not. You just want to use = here.


That doesn't make any sense. oss.str() returns a std::string. You can't stream a string into a string. You either need str = oss.str(), or use a standard stringstream instead, and do ss >> str.


the operator "<<" is usable for ostringstream and you are using it for a string. for string I think you can use append function:

str.append(oss.str());

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜