Re: INT to STR
From: red floyd (no.spam_at_here.dude)
Date: 11/05/03
- Next message: skscpp: "operator new/delete"
- Previous message: tom_usenet: "Re: std::setprecision"
- In reply to: Marcel: "INT to STR"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 05 Nov 2003 18:14:37 GMT
Marcel wrote:
> 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!
The other poster showed what to do. I'll explain why it happened.
>
> #include <iostream>
> #include <string>
>
> int main() {
>
> int red = 50;
Red is of type int.
> std::string temp = "";
>
> temp += "hello";
So far you're fine.
> temp += red;
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.
> std::cout << temp;
>
> std::cin.get();
>
> return 0;
> }
>
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 +=.
- Next message: skscpp: "operator new/delete"
- Previous message: tom_usenet: "Re: std::setprecision"
- In reply to: Marcel: "INT to STR"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|