C99的snprintf
打印到一個字符串,並保證不溢出緩衝區:
char msg[48];
snprintf(msg, sizeof(msg),
"Player %s has lost %d hitpoints", victim.name, damage);
snprintf
返回,將已被寫入了該字符串已經足夠大的字符數。因此,如果返回的值等於或大於緩衝區大小,則字符串將被截斷。
它是合法的,通過零緩衝區大小和一個空指針,這樣就可以通過使探測通話先做好自己的分配:
char *msg;
int n;
n = snprintf(NULL, 0,
"Player %s has lost %d hitpoints", victim.name, damage);
msg = malloc(n + 1);
n = snprintf(msg, n + 1,
"Player %s has lost %d hitpoints", victim.name, damage);
// do stuff with msg
free(msg);
在GNU編譯器,非sandard功能asprintf
會爲你做:
char *msg = asprintf("Player %s has lost %d hitpoints",
victim.name, damage);
// do stuff with msg
free(msg);
'的sprintf()'是你的答案 – Haris
你想要['sprintf的()'](http://linux.die.net/man/3/sprintf)? –
您可能會發現約翰卡馬克的這個功能有趣,如在Quake 3引擎中實現的:https://github.com/id-Software/Quake-III-Arena/blob/master/code/splines/q_shared.cpp( 700行)。請注意,您需要足夠深的緩衝區或嵌套調用會發生有趣的事情,當然,如果您正在編寫多線程代碼,這是一個很大的禁忌。 – szczurcio