6

So in Objective-C with Cocos2d, I'd use a NSMutableString with format to put a variable (score) into a string. I'd take that string and use a CCLabel to place it on the screen.

Using Cocos2D-x, I'm having trouble finding a way to get this result. A simple example would be great. Thanks!

David Small
  • 581
  • 1
  • 10
  • 25

2 Answers2

12
int score = 35;
float time = 0.03;
char* name = "Michael";
char text[256];
sprintf(text,"name is %s, time is %.2f, score is %d", name, time, score);
CCLabelTTF* label = CCLabelTTF::labelWithString(text,"Arial",20);
this->addChild(label);
m.ding
  • 3,172
  • 19
  • 27
  • the answer and source code is great, but perhaps i would point out to either go with std::string and its concatenating abilities, or sprintf with char* - mixing both is kind of odd (at least to me). – Loic Argelies Sep 21 '12 at 00:45
  • yeah true, I edited my answer. but does sprintf accept std::string? I can't remember. coz I personally prefer sprintf than use string to connect all numbers and digits together, just a bit complicated to me. – m.ding Sep 21 '12 at 01:10
  • 1
    You can use the `c_str()` method to convert an `std::string`. – alxcyl Sep 21 '12 at 08:35
5

A simpler solution to set the string at any given time (from here). First define a macro somewhere in your code.

#define ccsf(...) CCString::createWithFormat(__VA_ARGS__)->getCString()

Then you can change the string any time like this:

m_pScoreLabel->setString(ccsf("%d pts", mCurrentScore));
Coyote
  • 2,454
  • 26
  • 47