pistacchio pistacchio - 5 months ago 22
C Question

Creating C formatted strings (not printing them)

I have a function that accepts a string, that is:

void log_out(char *);

In calling it, I need to create a formatted string on the fly like:

int i = 1;
log_out("some text %d", i);

How do I do this in ANSI C?

Only, since
returns a int, this means that I have to write at least 3 commands, like:

char *s;
sprintf(s, "%d\t%d", ix, iy);

Any way to shorten this?


Use sprintf.

int sprintf ( char * str, const char * format, ... );

Write formatted data to string Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.

The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version).

A terminating null character is automatically appended after the content.

After the format parameter, the function expects at least as many additional arguments as needed for format.



Pointer to a buffer where the resulting C-string is stored. The buffer should be large enough to contain the resulting string.


C string that contains a format string that follows the same specifications as format in printf (see printf for details).

... (additional arguments)

Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.


// Allocates storage
char *hello_world = (char*)malloc(13 * sizeof(char));
// Prints "Hello world!" on hello_world
sprintf(hello_world, "%s %s!", "Hello" "world");