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

## 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 on other sites
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 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 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.

1. 1
2. 2
frob
16
3. 3
4. 4
5. 5

• 15
• 13
• 14
• 75
• 22
• ### Forum Statistics

• Total Topics
632145
• Total Posts
3004345

×