10

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.

1
  • Add the code that reads from the file into oss. Commented Feb 23, 2011 at 16:17

5 Answers 5

26
string str = oss.str(); // this should do the trick 
Sign up to request clarification or add additional context in comments.

8 Comments

@user: Perhaps you put garbage in?
garbage in? what do you mean?
@user: You are getting garbage out of your stringstream. Perhaps the reason is that you are putting garbage into it, with the code that's represented by "read a string from file and put to oss"...
ifstream ifs("file"); oss << ifs;
@user552279: well that's your problem. That's not the proper way to read from a file. Also, Why are you trying to read from a file into a stream? Odds are you can read from the file directly (it's a stream too!).
|
7

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

Comments

2

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

Comments

1

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.