Question

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!

Was it helpful?

Solution

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).

OTHER TIPS

    ostringstream os;
    os<<"HelloWorld"<<randomnumber;
    string s;
    s = os.str();

string s now contains the string you want as a string object.

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)

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)

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.

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++

With C++11:

showMessage("Hello world" + std::to_string(randomNumber));

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);

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top