In the following exmple, how 'd I use sprintf when I have a boolean type of variable?
What is supposed to replace ? in the sprintf statement ? Thanks.Code:char s[64];
bool bVar = false;
sprintf(s, "This is a boolean variable bVar = %?", bVar);
Printable View
In the following exmple, how 'd I use sprintf when I have a boolean type of variable?
What is supposed to replace ? in the sprintf statement ? Thanks.Code:char s[64];
bool bVar = false;
sprintf(s, "This is a boolean variable bVar = %?", bVar);
Not trying to be mean, but...
http://lmgtfy.com/?q=c+sprintf
sprintf() originates from C which didn't even have a boolean type, so there's no specifier for that. When creating C++ and making it (at least for a large part) compatible with old C code, no extra specifiers were added, since C++ has its own stream I/O facilities (<iostream> and such, you know...).
Googling "c sprintf" results in http://www.cplusplus.com/reference/cstdio/sprintf/ being first on the list. Going to that page, the first sentence reads: "Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by s."
If there is no specifier, then there is no specifier. You can't make something out of nothing, so asking "what is supposed to be the specifier" doesn't make sense. No one knows since none exists.
If anything, you need to cast it to a type that is known by sprintf() and ensure the type cast is safe.
Regards,
Paul McKenzie
No.
The behaviour is undefined. You can't guarantee that bVar matches the type supported by "%d". A bool's underlying type is implementation-defined -- it could be an 8-bit, 16-bit, 32-bit, 64-bit integer, you don't know. It's up to the implementation as to what a bool is underneath the hood. That's why I stated to cast bool to an integral type supported by sprintf().
Regards,
Paul McKenzie
a quick alternative could be simply:
Code:char s[64];
bool bVar = false;
sprintf(s, "This is a boolean variable bVar = %s", bVar ? "true":"false" );
A handy little function:
Then use %s, %c, or %d as said before.Code:inline const char * btoa(bool b){
return b ? "true" : "false";
}
inline char btoc(bool b){
return b ? 'T' : 'F';
}
inline int btoi(bool b){
return b ? 1 : 0;
}