| re: INT to STR
Marcel wrote:[color=blue]
> The small code underneath is displaying the text 'hello2' as output. I
> supposed it to display hello50. I think i will have to convert the int to a
> string or am i wrong? If so, what is the right command? Sorry i am a
> beginner....
>
> Thanks in advance![/color]
The other poster showed what to do. I'll explain why it happened.[color=blue]
>
> #include <iostream>
> #include <string>
>
> int main() {
>
> int red = 50;[/color]
Red is of type int.
[color=blue]
> std::string temp = "";
>
> temp += "hello";[/color]
So far you're fine.
[color=blue]
> temp += red;[/color]
There is no string::operator+=(int), however there is a string::operator+=(char).
So, what happens is that the standard conversion from int to char takes place, and operator+=(char) is called, and the character
with the value of 50 (which in ASCII is '2') is appended to your string.
[color=blue]
> std::cout << temp;
>
> std::cin.get();
>
> return 0;
> }
>[/color]
I suspect that you were expecting a std::string to behave similarly to a VB String variable. Alas, it doesn't work that way, and
you need to do the string conversion yourself before using +=. |