I would like to use the syntax that printf uses, using the %d, %s and adding values after to assign a value to a char[]. Is this possible?
e.g. Given an output of:
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
I’d like to assign that to char[] output;
How can this be done?
I tried:
sprintf(output, "now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
but that didn’t seem to work. Is sprintf used differently… or is that not what I should be using?
Thanks!
EDIT: It turned out I simply needed to increase the initialized length of output…
That should work fine provided you have enough space in the output buffer (at least 26 bytes) to take the largest string you’ll create:
You need:
"now: "."-- ::").You may also want to consider changing the format string to
"now: %04d-%02d-%02d %02d:%02d:%02d"so that the datetimes will line up if you’re outputting them, to avoid something like:when
looks so much better. You’ll notice I’ve left the
"\n"off the end – since this is the sort of code you see a lot in logging, you’d want the datetime to be in a format you could easily append to, something like:If I’ve misunderstood what you’re using this for, feel free to ignore the last few paragraphs.