tvaz
tvaz

Reputation: 107

get formatted string to a variable

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

Answers (3)

ForceBru
ForceBru

Reputation: 44838

You want either sprintf either snprintf:

Usage

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.

Documentation


Why is snprintf safe

snprintf writes output to the string str, under control of the format string format, that specifies how subsequent arguments are converted for output. It is similar to sprintf(3), except that size specifies the maximum number of characters to produce. The trailing nul character is counted towards this limit, so you must allocate at least size characters for str.

If size is zero, nothing is written and str may be null. Otherwise, output characters beyond the n-1st are discarded rather than being written to str, and a nul character is written at the end of the characters actually written to str. 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

Sourav Ghosh
Sourav Ghosh

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 to fprintf, except that the output is written into an array (specified by argument s) 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

John Bode
John Bode

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

Related Questions