Reputation: 5025
How to build up a string in C that includes parameters? Is there a way similar to fprintf
syntax to do it? For example here's a little testProg.c
:
int main(int argc, char *argv[]) {
printf("You are running %s program.\n", argv[0]);
// It will print: "You are running testProg.c program.\n"
char myString[];
// I want the string printed by printf to be saved inside myString[]
// ...
}
Upvotes: 2
Views: 63
Reputation: 17698
You can use snprintf
. First determine the buffer size for myString
that will fit the content. Then use snprintf
to fill in the content.
char myString[100] = "";
snprintf( myString, sizeof(myString), "You are running %s program.", argv[0] );
snprintf
is similar to fprintf
(which is the general version of printf
with the output stream being stdout
), so all control formats applied - details can be found in the standard:
7.21.6.5 The snprintf function
#include <stdio.h>
int snprintf(char * restrict s, size_t n,
const char * restrict format, ...);
Upvotes: 7