Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building formatted strings in C

Tags:

c

string

printf

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?

like image 250
Saeid Yazdani Avatar asked Jun 08 '26 02:06

Saeid Yazdani


2 Answers

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.

like image 64
unwind Avatar answered Jun 10 '26 18:06

unwind


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;
}
like image 26
perreal Avatar answered Jun 10 '26 18:06

perreal