Log() only works with string literals

Hello friends…
i would like to print a variable value into console, but it is not doing…

void init(){
     //... all default events and expressions...
     this->scheduleUpdate();
}

void update(float dt){
     log("A");       //this prints fine...
     log(myVar);  //this prints nothing
}

myVar is a float declared on header…

I have tried with std::cout too with no result… is there any other way to print variables?

Thanks!

Those are the ways.

Sounds like myvar is out of scope? Check in the debugger.

1 Like

cocos2d::log supports format specifiers and a variable list of arguments:

#define CCLOG(format, ...) cocos2d::log(format, ##__VA_ARGS__)

So, for example, to print the value of myVar:
CCLOG("%d", myVar);

3 Likes

log() and CCLOG() follow the printf() formatting rules. See this cheatsheet.

It’s pretty straightforward but note that this API is really a C API and not a C++ API so therefore won’t handle C++ objects. If you want to print the contents of a std::string (a standard C++ string) then you need to pass the C const char * via the c_str() method:

std::string s = "world";
log("hello %s", s.c_str());
4 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

This is actually so useful. I need to remember this more often.