snprintf函式的常見功能

2021-06-21 15:44:43 字數 1055 閱讀 4333

以前將各種整型數浮點數轉換為字串時都要借助stringstream類,不僅麻煩,而且對stringstream的了解不夠,經常出現一些奇怪的錯誤,現在有了snprintf,類似的轉換功能實現起來相當容易。下面轉入正題。

使用snprintf函式前,要記住包含標頭檔案

下面的函式宣告摘自部落格snprintf函式用法,但原文沒有提到如何實現基本資料型別與字串的轉換。

int snprintf(char *restrict buf,  size_t n,  const char * restrict  format, ...);

函式說明:最多從源串中拷貝n-1個字元到目標串中,然後再在後面加乙個0。所以如果目標串的大小為n 的話,將不會溢位。

函式返回值:若成功則返回欲寫入的字串長度,若出錯則返回負值。

(以下程式均在dev-c++上通過)

1、整型數字轉換為字串。

#include#include#includeusing namespace std;

int main()

輸出結果為:12

2、浮點型轉換為字串。

#include#include#includeusing namespace std;

int main()

輸出結果為:

12.532423

12.53

3、拷貝字串。

#include#include#includeusing namespace std;

int main()

輸出結果:

dskcdsvkj

dskcdsvkjgch

使用snprintf的另乙個好處是可以實現字串的連線,再加上其相對安全的功能,strcat基本就可以拋棄了

#include#include#includeusing namespace std;

int main()

輸出結果:

dskc

dskcdskc

snprintf函式的使用

函式原型 int snprintf char str,size t size,const char format,功能 將可變個引數 按照format格式化成字串,然後將其複製到str中 1 如果格式化後的字串長度 size,則將此字串全部複製到str中,並給其後新增乙個字串結束符 0 2 如果格式...

snprintf函式用法

int snprintf char restrict buf,size t n,const char restrict format,函式說明 最多從源串中拷貝n 1個字元到目標串中,然後再在後面加乙個0。所以如果目標串的大小為n的話,將不會溢位。函式返回值 若成功則返回欲寫入的字串長度,若出錯則返...

snprintf函式用法

int snprintf char restrict buf,size t n,const char restrict format,函式說明 最多從源串中拷貝n 1個字元到目標串中,然後再在後面加乙個0。所以如果目標串的大小為n的話,將不會溢位。函式返回值 若成功則返回欲寫入的字串長度,若出錯則返...