是否有像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