Creating C formatted strings (not printing them)

前端 未结 7 1044
广开言路
广开言路 2020-12-04 12:07

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:

7条回答
  •  一个人的身影
    2020-12-04 12:34

    It sounds to me like you want to be able to easily pass a string created using printf-style formatting to the function you already have that takes a simple string. You can create a wrapper function using stdarg.h facilities and vsnprintf() (which may not be readily available, depending on your compiler/platform):

    #include 
    #include 
    
    // a function that accepts a string:
    
    void foo( char* s);
    
    // You'd like to call a function that takes a format string 
    //  and then calls foo():
    
    void foofmt( char* fmt, ...)
    {
        char buf[100];     // this should really be sized appropriately
                           // possibly in response to a call to vsnprintf()
        va_list vl;
        va_start(vl, fmt);
    
        vsnprintf( buf, sizeof( buf), fmt, vl);
    
        va_end( vl);
    
        foo( buf);
    }
    
    
    
    int main()
    {
        int val = 42;
    
        foofmt( "Some value: %d\n", val);
        return 0;
    }
    

    For platforms that don't provide a good implementation (or any implementation) of the snprintf() family of routines, I've successfully used a nearly public domain snprintf() from Holger Weiss.

提交回复
热议问题