TLD
TLD

Reputation: 8135

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

Upvotes: 10

Views: 18487

Answers (5)

Mehrnaz Zadeh
Mehrnaz Zadeh

Reputation: 25

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());

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

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);

Upvotes: 7

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

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.

Upvotes: 1

Karl Bielefeldt
Karl Bielefeldt

Reputation: 49148

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

Upvotes: 2

Simone
Simone

Reputation: 11797

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

Upvotes: 26

Related Questions