是否有像printf这样的函数可以返回一个字符串而不是打印它?我有一个函数用特定的颜色打印字符串,但它必须是字符串文字,而不是像printf那样接受变量。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");
如果我想打印颜色与变量,它不会工作。像pYellow("Num: %d", 42);
会给出一个错误,因为它有太多的参数。做pYellow(printf("String"));
也不行。
TL:DR我想知道是否有printf方法返回一个字符串,而不是打印它。
您可以使用'dom0'建议的snprintf,或者您可以使用一个动态分配内存并返回一个指针的函数。有一种叫做'asprintf'的非标准格式,但是你可以通过委托给'vsnprintf'在几行中用标准C实现它。 – 2014-10-10 02:07:12
http://en.cppreference.com/w/cpp/io/c/fprintf – 2014-10-10 02:09:11
另请参见[AIX上'asprintf()'的替代或替代方法](http://stackoverflow.com/questions/4899221/substitute - 或解决方法换asprintf-ON-AIX)。 – 2014-10-10 18:29:26