一、概述
cstring.format函數是C++語言中非常常用的字元串格式化函數之一,可以將一組參數按照一定的格式輸出到字元串中。
該函數定義如下:
int snprintf(char *str, size_t size, const char *format, ...);
其作用是將一組參數(format之後的參數)按照format參數中的格式輸出到字元串str中,最多輸出size個字元,返回實際輸出的字元數。
二、使用方法
cstring.format函數的使用非常簡單,只需要設置好參數即可。其中,第一個參數是輸出的目的地字元串,第二個參數是目的地字元串的最大長度,第三個參數是格式化字元串,之後的參數是要輸出的參數,按照格式化字元串中的佔位符進行替換。
佔位符的形式為 % + 字元,其中常用的字元有:d(10進位整數),u(10進位無符號整數),o(8進位整數),x(16進位整數),c(char),s(string)等。
以下是一個例子:
#include <cstring> #include <iostream> using namespace std; int main() { char output[100]; sprintf(output, "My name is %s, my age is %d.", "Tom", 18); cout << output << endl; return 0; }
上面的代碼中,輸出的字元串是”My name is Tom, my age is 18.”。
三、常見問題
1、格式化字元串中的轉義字元
格式化字元串中可能含有%n、%t等轉義字元,這時候需要使用%%表示一個百分號。
例如:
char output[100]; sprintf(output, "My salary is %d%%.", 10);
輸出的字元串是”My salary is 10%.”。
2、輸出的字元數大於目的地字元串長度
如果輸出的字元數大於目的地字元串長度,則會截斷目的地字元串,只將前面的字元輸出。所以需要保證目的地字元串的長度足夠長,以免數據丟失。
3、不同平台的格式化字元串
在不同的平台上,格式化字元串的實現可能有所不同,因此需要注意使用不同平台的兼容性問題。
四、實例代碼
#include <iostream> #include <cstdio> using namespace std; int main() { char output[100]; sprintf(output, "%05d", 10); printf("%s\n", output); sprintf(output, "%.2f", 1.2345); printf("%s\n", output); sprintf(output, "%c", 'a'); printf("%s\n", output); return 0; }
原創文章,作者:ZZEMY,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/371444.html