Jump to content
  • Advertisement
Sign in to follow this  
darenking

SOLVED: C++ ostringstream problems...

This topic is 4764 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm using std::ostringstream. It works perfectly well, but there's something odd.
	std::ostringstream buffer;
	buffer << "data/00" << level << ".txt";

	std::string filename;
	filename = buffer.str();

	std::ifstream file(filename.c_str());


In the above code, I create a stream called 'buffer' and use it to create a filename, 'data/001.txt' or whatever. I then need to convert the buffer to a C style string so that I can use it with ifstream, but as far as I know you can't do it directly, you have to convert it to a C++ string object first. This seems a bit messy! Is there a simpler way? [Edited by - darenking on August 1, 2005 3:09:32 PM]

Share this post


Link to post
Share on other sites
Advertisement
There is no need whatsoever to actually copy the internal string out to a separate string object. std::ifstream file(filename.str().c_str()); works just fine.

Share this post


Link to post
Share on other sites
Which does in fact copy it to a separate string object, however it's a temporary.

Also, you might like:


buffer << "data/" << std::setfill('0') << std::setw(3) << level << ".txt";


that is, if 'level' is a number, and you want it zero-filled like that, and it's 3 digits wide...

Share this post


Link to post
Share on other sites
Perhaps you'll find this interesting as well :)

Then you could do something like

std::ifstream file(text("data/")(std::setfill('0'))(std::setw(3))(level)(".txt"));

(after providing an implicit const char* cast in the same style as the provided std::string cast). Although providing this sort of cast in general is a bad idea (hence why strings and stringstreams themselves don't :) ), since they could be invoked when you wouldn't expect them.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!