INT to STR

M

Marcel

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!

#include <iostream>
#include <string>

int main() {

int red = 50;

std::string temp = "";

temp += "hello";

temp += red;

std::cout << temp;

std::cin.get();

return 0;
}

Regards,

Marcel
 
K

keanu

Marcel wrote in said:
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!

#include <iostream>
#include <string>
#include <sstream>
template<typename T> std::string toStr(T var) {
std::eek:stringstream tmp; tmp << var; return tmp.str();
}
int main() {
int red = 50;
std::string temp = "";
temp += "hello";
//temp += red;
 
M

Marcel

keanu said:
#include <sstream>
template<typename T> std::string toStr(T var) {
std::eek:stringstream tmp; tmp << var; return tmp.str();
}
//temp += red;


Thanks a lot,

That's more complicated than i expected!

Marcel
 
R

red floyd

Marcel said:
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::eek:perator+=(int), however there is a string::eek:perator+=(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 +=.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Infinite loop problem 1
converting double to int 1
TypeError: Can't convert 'int' object to str implicitly 12
Chatbot 0
Crossword 2
I need help 1
int*unsigned int = unsigned? 2
int to char problem ? 4

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top