Reputation: 107
Is there any C function (or a way) to get a formatted string as a normal string?
For example:
printf("this is %s", "a message")
I want printf()
s output "this is a message"
in a char*
variable. This should be simple but I'm not coming with something besides write it to a file and read it or concatenate as many times as needed.
So, is there a function or an easy way to put any formatted string into a single string variable in C?
Upvotes: 5
Views: 10671
Reputation: 44838
You want either sprintf
either snprintf
:
char str[128];
//sprintf(str, "hello %s", "world");
snprintf(str, 128, "hello %s", "world");
Note that snprintf
is safer since it will cut the string to appropriate length of encountered overflow.
snprintf
safe
snprintf
writes output to the stringstr
, under control of the format string format, that specifies how subsequent arguments are converted for output. It is similar tosprintf(3)
, except thatsize
specifies the maximum number of characters to produce. The trailing nul character is counted towards this limit, so you must allocate at leastsize
characters forstr
.If
size
is zero, nothing is written and str may be null. Otherwise, output characters beyond then-1
st are discarded rather than being written tostr
, and a nul character is written at the end of the characters actually written tostr
. If copying takes place between objects that overlap, the behaviour is undefined.On success, returns the number of characters that would have been written had size been sufficiently large, not counting the terminating nul character. Thus, the nul-terminated output has been completely written if and only if the return value is nonnegative and less than size. On error, returns -1 (i.e. encoding error).
That is, snprintf
protects programmers from buffer overruns, while sprintf
doesn't.
Upvotes: 9
Reputation: 134336
Yes, the function you're lokng for is sprintf()
/snprintf()
.
Quoting C11
, chapter §7.21.6.5, The snprintf()
function
int snprintf(char * restrict s, size_t n, const char * restrict format, ...);
The
snprintf
function is equivalent tofprintf
, except that the output is written into an array (specified by arguments
) rather than to a stream.
It writes the formatted string into the array supplied as the first argument to it.
FWIW, these function do not handle the allocation (or checking, for that matter) of memory to the supplied buffer (array). While passing the array, you need to make sure the destination is long enough to hold the final result.
Upvotes: 3
Reputation: 123468
Use sprintf
:
sprintf( var, "this is %s", "a message" );
Note that var
must be big enough to store the final string (including the string terminator).
Upvotes: 4