Creating C formatted strings (not printing them)

前端 未结 7 1041
广开言路
广开言路 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:27

    I haven't done this, so I'm just going to point at the right answer.

    C has provisions for functions that take unspecified numbers of operands, using the header. You can define your function as void log_out(const char *fmt, ...);, and get the va_list inside the function. Then you can allocate memory and call vsprintf() with the allocated memory, format, and va_list.

    Alternately, you could use this to write a function analogous to sprintf() that would allocate memory and return the formatted string, generating it more or less as above. It would be a memory leak, but if you're just logging out it may not matter.

提交回复
热议问题