I’m trying to format a char array with sprintf() for an arduino project in C++
My goal is to format the following integers: day,month,year,hour,minute and second into the following
DD/MM/YYYY HH:MM:SS
My issue arises when an integer is < 10 I loose the format which I try and correct with the following sprintf
sprintf (timeStr, "%c%u/%c%u/%u %c%u:%c%u:%c%u",(monthDay>0 && monthDay<=9)?'0':'',monthDay,(month>0 && month<=9)?'0':'',month,year,(hour>0 && hour<=9)?'0':'',hour,(minute>0 && minute<=9)?'0':'',minute,(second>0 && second<=9)?'0':'',second);
Now this wont compile because i get “empty character constant” which I assume comes from the ” not having a legal value.
I’m stuck on how I can use sprintf to format a string if the %c in the statement is conditional and I only want a value if its <10
If anyone has any insight into how I could achieve this I would highly appreciate it as I’m really stuck on it!
Thank you!
You’re correct that
%crequires a character (which an empty''is not, by the way).But, if you’re after zero-padding, just use the format specifier
"%02d"? That’s how you normally get zero-padded numbers. In other words, use:Many embedded systems may exclude floating point specifiers (or may make them optional) in order to preserve space but zero-padding or space-padding integers is a fairly simple operation that they all should have.
If you find an implementation so deficient that it doesn’t support them, you can use strings instead of characters, since the empty string is valid:
But I’m pretty certain Arduino isn’t that deficient.