String::createWithFormat %s problem

Hi guide, i would like to create a string using String::createWithFormat to combine numbers and other strings as code below:

int number1 = 4;
int number2 = 3;
cocos2d::String* mathematicalOperationName = String::create("+");
cocos2d::String* questionMark = String::create("?");
cocos2d::String* mathExpression = String::createWithFormat("%d %s %d = %s", number1, mathematicalOperationName->getCString(), number2, questionMark->getCString());

My desire string is “4 + 3 = ?”
But i got the result is " 4 3 = "

I don’t know what happen and how to fix this?

I’ve solved this by used the StringUtils.

int number1 = 4;
int number2 = 3;
std::string mathematicalOperationName = StringUtils::format("%s", "+");
std::string questionMark = StringUtils::format("%s", "?");
std::string mathExpression = StringUtils::format("%d %s %d = %s", this->number1, this->mathematicalOperationName.c_str(), this->number2, this->questionMark.c_str());

Just FYI you can use + operator or std::stringstream as well to build up strings.

std::string mathematicalOperationName = "+";
std::string questionMark = "?"; 
std::string mathExpression = std::to_string(this->number1) + " " this->mathematicalOperationName + " " + std::to_string(this->number2) + " = " + this->questionMark;

// or with stringstream
#include <stringstream>
std::stringstream ss;
ss << this->number1 << " " << this->mathematicalOperationName << " " << this->number2 << " = " << this->questionMark;
std::string mathExpression = ss.str();
1 Like

Thank for your help.
I have some doubt.
I wonder if using stringstream consuming a lot of memory?

Well definitely something I would measure if you’re worried about memory or performance. Usually you won’t have any memory issues with string creation compared to loading and caching textures. You could also set stringstream capacity and keep it around clearing it out as necessary which I believe would only alloc memory once.

I’ve moved mostly to std::string appends and only StringUtils::format where necessary for the specific printf style formatting. I use stringstream anywhere that I build up a long string. StringUtils::format is actually quite heavy based on profiling I’ve done vs. std::string + std::string

I now mostly use std::string instead of char* and it always feels wrong and annoying to use .c_str() all over the place.

YMMV of course :smile: