printf That Returns a String [duplicate]

2019-08-30 19:21发布

问题:

This question already has an answer here:

  • sprintf() with automatic memory allocation? 5 answers

Is there a function like printf that can return a string instead of printing it? I have a function that prints a string in a certain color, but it has to be a string literal instead of accepting variables like printf.

// Function declaration (Assums YELLOW and NORMAL are the unix constants for terminal colors
void pYellow(char *str) {
    printf("%s%s%s", YELLOW, str, NORMAL);
}

//Function call 
void pYellow("This is a string");

If I wanted to print in color with a variable, it wont work. Like pYellow("Num: %d", 42); will give an error, because its got too many parameters. And doing pYellow(printf("String")); won't work either.

TL:DR I want to know if there's a printf method that returns a string instead of printing it.

回答1:

Use snprintf:

int snprintf(char *str, size_t size, const char *format, ...);
  • str is a buffer you allocated (e.g. malloc())
  • size is the size of that buffer
  • After the call the formatted string is stored in str.
  • There's also sprintf, never use it

Also you can create you own printf-like functions using the v*printf family of functions. Simplest example for this:

#include <stdarg.h>
// required for va_list, va_start, va_end

void customPrintf(const char* format, /* additional arguments go here */ ...)
{
    va_list args;
    va_start(args, format);
    // set color here (for example)
    vprintf(format, args);
    // reset color
    va_end(args);
}