Reputation: 399
I have been working in Java since I started programming and decided to learn c++. What I wrote in Java looked like this:
showMessage("Hello world" + randomNumber);
And it showed text + integer or float or whatever. But it wont work in c++.
Error message by xCode: Invalid operands to binary expression ('const char *' and 'float')
Cheers!
Upvotes: 1
Views: 1093
Reputation: 76305
With C++11:
showMessage("Hello world" + std::to_string(randomNumber));
Upvotes: 0
Reputation: 3182
I am not sure if c-style answer is fine, but I have already answer it here in a cocos2d-x question.
Trying to set up a CCLabelTTF with an integer as part of it's string in Cocos2d-X C++
Upvotes: 0
Reputation: 145279
Define a class S
. Then write
showMessage( S() << "Hello world" << randomNumber );
I've coded up the S
class too many times for SO, and it's a good exercise to create it, hence, not providing the source code.
Note that you can reasonably call it StringWriter
or something like that, and then just use a typedef
for more concise code in function calls.
Upvotes: 0
Reputation: 40703
In C++ the standard way to concatenate strings and primitives is to use stringstream
. Which fulfils the same functionality (and a little bit more) as StringBuilder
in Java (of course its API differs). However, if you are comfortable using cout
then you should be fine.
eg.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main () {
stringstream ss;
ss << "Some string - " << 124; // build string
string str = ss.str(); // extract string
cout << str << endl;
return 0;
}
Quick reference for stringstream http://www.cplusplus.com/reference/iostream/stringstream/stringstream/
Upvotes: -1
Reputation:
Consider adding a new function that is able to convert several types to std::string:
template<typename ty>
string to_str(ty t)
{
stringstream ss; ss << t;
return ss.str();
}
Usage:
"Hello World " + to_str(123)
Upvotes: 1
Reputation: 143091
You can do a sprintf
according to Anton, or to be more c++
:
std::stringstream ss;
ss << "Hello, world " << randomNumber;
showmessage(ss.str());
(there's nothing wrong with sprintf, especially if you use snprintf
instead).
Upvotes: 2
Reputation: 5546
Also you can use boost::lexical_cast to cast numbers into strings which is fastest method in most cases:
showMessage("Hello world" + boost::lexical_cast<std::string>(randomNumber));
showMessage declaration is
void showMessage(cosnt std::string& message)
Upvotes: 1
Reputation: 14039
ostringstream os;
os<<"HelloWorld"<<randomnumber;
string s;
s = os.str();
string s now contains the string you want as a string object.
Upvotes: 1
Reputation: 3509
you should print into the char* instead.
You could do something like
char* tempBuffer = new char[256];
sprintf_s(tempBuffer, 256, "Hello world %d", randomNumber);
showMessage(tempBuffer);
Upvotes: -1