sprintf acting weird

Hey,

I have this simple bit of code that prints out todays date and time (hard coded for testing purposes). When i run the code below, the month is ignored. if I remove the the sprintf line that handles the DAY, then the month shows up fine. The sprintf are used to add some zero paddings.

Thoughts?

  int myYear = 2019;//now.year();
  int myMonth = 2;//now.month();
  int myDay = 7;//now.day();
  int myHour = 3;//now.hour();
  int myMinute = 5;//now.minute();
  int mySecond = 9;//now.second();

  char c_year[4];
  char c_month[2];
  char c_day[2];
  sprintf(c_year, "%04d", myYear);
  sprintf(c_month, "%02d", myMonth);
  sprintf(c_day, "%02d", myDay);

  Serial.print(c_year);
  Serial.print("/");
  Serial.print(c_month);
  Serial.print("/");
  Serial.println(c_day);

You need to add 1 to each one of your string declaration to account for 0-terminated string.

char c_year[5];
char c_month[3];
char c_day[3];

ooooohhhhh, thank you so much. i spent way too much time on such a silly thing.

No problem. I’ve done it myself!

Also consider using snprintf() instead of sprintf()
With that, you specify in addition the size of the buffer that is to be filled which prevents any overflow corrupting storage. This is particularly useful where there is a complex format specifier as this increases the risk that the user underestimates the final length of the formatted string.

For the same amount of buffer space, (11 bytes), you could do it all in a single sprintf() and a single Serial.print() instead of multiple calls.

i.e.

char buf[11];
snprintf(buf, "%04d/%02d%/02d", sizeof(buf), myYear, myMonth, myDay);
Serial.print(buf);

NOTE:
As pointed out by sterretje, the snprintf() arguments above are incorrect; it should be:

snprintf(buf, sizeof(buf), "%04d/%02d%/02d", myYear, myMonth, myDay);

And Several 3rd party cores have included a printf() method in the Print class so you can use it directly on the Serial object.
I.e.:

Serial.printf("%04d/%02d%/02d", myYear, myMonth, myDay);

So if you have a ESP8266, ESP32, chipkit, or Teensy product you can avoid doing the intermediate buffer and sprintf()

— bill

@bperrybap
I know that you know but the size (of the buffer) is the second argument in the snprintf function.

sterretje:
@bperrybap
I know that you know but the size (of the buffer) is the second argument in the snprintf function.

oops. Obviously too late for me to be posting....
--- bill