Concatenate a string with an int.
Aug 6, 2008 at 10:19pm Aug 6, 2008 at 10:19pm UTC
Hello people, I'm having trouble trying to concat a string with an int type.
I want to put the value of the int inside the string.
The ideia is something like this:
1 2 3
int myInt = 265;
string myString = "The number is" myInt;
cout << myString;
The console should print:
The number is 265
But, doesn't matter what I try, the compiler (Dev-C++) always says:
invalid conversion from `int' to `const char*'
Or anything else saying that it's not possible...
What should I do to make this works?
Aug 6, 2008 at 10:44pm Aug 6, 2008 at 10:44pm UTC
A string and an int are two incompatible types of things. You can't concatenate them.
You must first convert the int to a string.
You can have
cout do it for you:
cout << "The number is " << myInt;
or you can #include <sstream> and use a string stream:
1 2 3
stringstream ss;
ss << "The number is " << myInt;
cout << ss.str();
Hope this helps.
Aug 6, 2008 at 11:00pm Aug 6, 2008 at 11:00pm UTC
The problem isn't print both together (the 1st option "cout"), but is put them together inside another string.
I have a function that calls another one and one of the params is the string... Something like this:
1 2 3 4 5
int myFunc(){
int myInt = 265;
string myString = "The number is" + myInt;
anotherFunc(myString)
}
Aug 6, 2008 at 11:10pm Aug 6, 2008 at 11:10pm UTC
Then do the second method
#include <sstream> at the top of the file
then
1 2 3 4 5 6
int myFunc() {
int myInt = 256;
string myString; // declare the string
myString << "The number is " << myInt;
anotherFunc(myString);
}
the <sstream> header will let you do the same as cout only storing the output into a string variable instead of printing to console.
Aug 6, 2008 at 11:29pm Aug 6, 2008 at 11:29pm UTC
Thanks, now it makes sence..
But, still having one problem:
1 2 3 4
int myInt = 100
stringstream myString;
myString << "You lose" << myInt << " HP" ;
myFunc(myString);
Dev-C++ says:
conversion from `std::stringstream' to non-scalar type `std::string' requested
Aug 7, 2008 at 3:48am Aug 7, 2008 at 3:48am UTC
Aakanaar just forgot to use
.str() to get a
string out of that
stringstream .
1 2 3 4
int myInt = 100
stringstream myString;
myString << "You lose" << myInt << " HP" ;
myFunc(myString.str());
Enjoy!
Last edited on Aug 7, 2008 at 3:48am Aug 7, 2008 at 3:48am UTC
Aug 7, 2008 at 6:37am Aug 7, 2008 at 6:37am UTC
Bah, sorry. I'm only human. :-)
I've not actually used stringstream yet, myself. I'm posting from what I''ve learned from reading threads on here.
Aug 7, 2008 at 7:10am Aug 7, 2008 at 7:10am UTC
Many many thanks, Duoas and Aakanaar.
Now works perfectly...
ps: Sorry Duoas, I don't gave enough attention to your 1st post...
Topic archived. No new replies allowed.