
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - sprintf() 函式
C 庫的 sprintf() 函式允許您建立具有指定格式的字串,類似於 printf(),但它不是列印到標準輸出,而是將生成的字串儲存在使用者提供的字元陣列中。
語法
以下是 C 庫 sprintf() 函式的語法:
int sprintf(char *str, const char *format, ...);
引數
此函式接受以下引數:
- str:指向字元陣列的指標,生成的字串將儲存在此處。
- format:指向一個以 null 結尾的字串的指標,該字串包含要寫入字串 str 的文字。此字串可能包含格式說明符,這些說明符指示如何將後續引數轉換為格式並格式化到生成的字串中。
返回值
sprintf() 函式返回寫入字串 str 的字元數,不包括 null 終止字元。
示例 1:格式化浮點數
這裡,sprintf() 以兩位小數格式化浮點數。
以下是 C 庫 sprintf() 函式的示例。
#include <stdio.h> int main() { char buffer[100]; float pi = 3.14159; sprintf(buffer, "The value of pi is %.2f.", pi); printf("%s\n", buffer); return 0; }
輸出
以上程式碼產生以下結果:
The value of pi is 3.14.
示例 2:組合字串和整數
此示例展示了 sprintf() 如何將字串和整數組合到一個格式化的字串中。
#include <stdio.h> int main() { char buffer[100]; int age = 30; char name[] = "John"; sprintf(buffer, "%s is %d years old.", name, age); printf("%s\n", buffer); return 0; }
輸出
執行以上程式碼後,我們得到以下結果:
John is 30 years old.
廣告