Defining a string as in fprintf syntax


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[]
   // ...

Show source
| C   | string   2017-01-02 10:01 1 Answers

Answers ( 1 )

  1. 2017-01-02 10:01

    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: The snprintf function

         #include <stdio.h>
         int snprintf(char * restrict s, size_t n,
              const char * restrict format, ...);
◀ Go back