Lets say I have lots of printf usage, but I want to store them in a string and print them all in one go. Imagine the case below:
printf("%d,", _counter);
printf("IS REAL,", _condition);
printf("%f,", _value);
printf("%d,\r\n", _time);
What I want to do is to build a string and use printf only once when I am sure that I want to print it on screen. For example the output of above code will be:
1,IS REAL,663,1044
In C# I would use StringBuilder....but how to do this in C?
You use sprintf(), or (much better) snprintf().
char buffer[32];
snprintf(buffer, sizeof buffer, "%d,IS REAL,%f,%d\r\n", _counter, _value, _time);
printf("%s", buffer);
I skipped the _condition variable access, since that line didn't do any formatting.
As suggested, sprintf is what you are asking I believe, however, you can always do this:
printf("%d, IS REAL(%d), %f, %d,\r\n", _counter, _condition, _value, _time);
and sprintf returns the number of characters written so you can use it like so:
#include <stdio.h>
#include <string.h>
int main() {
char buf[256];
int s = sprintf(buf, "This %d,", 12);
s += sprintf(buf+s, "and this %f.", 1.0);
s += sprintf(buf+s, ",also %f", 2.0);
printf("%s\n", buf);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With