Jump to content
  • Advertisement
Sign in to follow this  
Graham

Overload std::String operator+

This topic is 4886 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 would like to have the ability to do stuff like this in my code:
string str("Answer is ");
int num = 42;
string str2 = (str + num);

But I get compile errors. I tried writing my own version of the operator but I get link errors because the operator is already define.
string operator+(const string& lhs, const int& num)
{
	char pstr[15];
	itoa(num, pstr, 10);
	string str = lhs + pstr;
	return str;
}

Thanks for any help.

Share this post


Link to post
Share on other sites
Advertisement
Look into std::stringstream, and the sstream header. Using a stringstream, you can have a text buffer as the target for C++ stream operations. Eg:

	string str("Answer is ");
int num = 42;
stringstream str2;
str2 << str << num;


There may be more suitable alternatives. I haven't done much of this kind of thing on strings in C++.

Share this post


Link to post
Share on other sites
Thanks for that it worked great for integers. When I used a float it rounded after 4 decimal places. std::setw(10) did not help. Any thoughts?

edit: I should have used setprecision(10) which does work. Although if I want to show 10 decimal places and the number has only 5 there is some random stuff. How do I should the first 10 or less decimal places.

Graham.

Share this post


Link to post
Share on other sites
setprecision() will by default show additional characters past the decimal point up to the amount indicated, only if they are not zero. The problem with random junk you're getting will be due to the limits of floating point precision. With a single precision floating point number, you only have around 6-7 digits of accuracy. Round-off error makes the rest useless, so don't try and output 10 characters when only the first 6-7 will be accurate. If you want a set number of decimal places to be written, even if they're zero, my documentation tells me ios::showpoint should be able to enable this behaviour.

Anyway, stringstream inherits from ios_base, so all the same manipulators that apply for streams apply for a stringstream.

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!