Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy value from ostringstream to string?

Tags:

c++

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 the value of the string, it prints out "....0xbfad75c40xbfad75c40xbf...." likes memory address.
Can anybody tell me why? Thank you.

like image 861
Xitrum Avatar asked Feb 23 '11 14:02

Xitrum


2 Answers

string str = oss.str(); // this should do the trick
like image 103
Simone Avatar answered Sep 22 '22 00:09

Simone


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);
like image 23
Benjamin Lindley Avatar answered Sep 22 '22 00:09

Benjamin Lindley