Reputation: 14112
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?
Upvotes: 3
Views: 8742
Reputation: 399833
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.
Upvotes: 8
Reputation: 97948
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;
}
Upvotes: 3
Reputation: 22084
To answer your qeustion, you can add as many formatters or strings as you want.
printf("%d,IS REAL,%f,%d,\r\n", _counter, _value, _time);
Note, that I ommited this one:
printf("IS REAL,", _condition);
because you are goiving it as an argument, but didn't specify a format for it, just plain text, so it would be wrong. If you want to print _condition
as value, then you must add also a format specifier like %d
or whatever _condition
is. If it is a boolean you could do something like this:
printf(""%s,", (_condition == 1) ? "IS REAL" : "IS NOT");
But I don't know your code, so this is just a suggestion assuming you want something like this done.
If you want to build a string in memory, collecting all the data first, you have to use s(n)printf
, but then you must make sure to allocate and deallocate enough space for your string.
Upvotes: 1
Reputation: 13270
create a function that takes the current string and the chunk that you want to plug on as arguments,
then malloc a new pointer on char with a length equal to (strlen(string) + strlen(chunk) + 1)
you can use sprintf let say:
sprintf(newstring, "%s%s", string, chunk);
then free the last two string if you allocate them manually.
Returns the pointer of the new string.
Upvotes: 0