Stephen Liu
在C語言編程中,我們不可避免的要接觸到可變參數函數,對於不支持函數多態的C語言來講,使用可變參數和宏定義函數是變通的實現函數多態的好方法。在進一步涉及到可變參數函數之前,我們先來看看常用到的兩個可變參數的典型,分別是vsprintf和sprintf。
一、vsprintf函數
Header File
stdio.h
Category
Memory and String Manipulation Routines
Prototype
int vsprintf(char *buffer, const char *format, va_list arglist);
int vswprintf(wchar_t *buffer, const wchar_t *format, va_list arglist);
Description
Writes formatted output to a string.
The v...printf functions are known as alternate entry points for the ...printf functions. They behave exactly like their ...printf counterparts, but they accept a pointer to a list of arguments instead of an argument list.
vsprintf accepts a pointer to a series of arguments, applies to each a format specifier contained in the format string pointed to by format, and outputs the formatted data to a string. There must be the same number of format specifiers as arguments.
Return Value
vsprintf returns the number of bytes output. In the event of error, vsprintf returns EOF.
--對照翻譯
頭文件
stdio.h
分類
內存和字符串操作
函數原型
int vsprintf(char *buffer, const char *format, va_list arglist);
int vswprintf(wchar_t *buffer, const wchar_t *format, va_list arglist);
描述
寫格式化後的輸出到一個字符串
v..printf函數族是..print函數族的可替代函數,他們像..printf函數族一樣操作,但是他們接受指向參數列表的指針而不是參數列表。
vsprintf接受一個指向一系列可變參數的指針,提供給每一個參數一個包含在form中的格式化定義,並且輸出格式化後的數據到一個字符串中,格式定義和參數數量必須相等。
返回值
vsprintf返回輸出的字節數目,出錯時返回EOF
二、sprintf函數
Header File
stdio.h
Category
Memory and String Manipulation Routines
Prototype
int sprintf(char *buffer, const char *format[, argument, ...]);
int swprintf(wchar_t *buffer, const wchar_t *format[, argument, ...]);
Description
Writes formatted output to a string.
Note: For details on format specifiers, see printf.
sprintf accepts a series of arguments, applies to each a format specifier contained in the format string pointed to by format, and outputs the formatted data to a string.
sprintf applies the first format specifier to the first argument, the second to the second, and so on. There must be the same number of format specifiers as arguments.
Return Value
On success, sprintf returns the number of bytes output. The return value does not include the terminating null byte in the count.
On error, sprintf returns EOF.
--對照翻譯
頭文件:
stdio.h
頭文件
stdio.h
分類
內存和字符串操作
函數原型
int sprintf(char *buffer, const char *format[, argument, ...]);
int swprintf(wchar_t *buffer, const wchar_t *format[, argument, ...]);
描述
寫格式化後的輸出到一個字符串
注意:對於格式化定義規範,參看printf
sprintf接受一系列參數,提供給每一個參數一個格式化定義,並且輸出格式化數據到字符串
sprintf提供給首個參數第一個格式化定義,第二個賦予次個格式化定義,格式化定義數量必須和參數數量一致
返回值
成功,返回輸出的字節數量,返回值不包含終止null字節的字節數量
錯誤,返回EOF
爲了便於比較這兩個函數的使用,下面給出一個程序片段:
char szBuffer[256];
sprintf(szBuffer, "welcome %d, %s", 1, "hi");
ShowMessage(szBuffer);
vsprintf(szBuffer, "welcome %d, %s", 1, "hi"); //<-提示[C++ Error] Unit1.cpp(24): E2034 Cannot convert 'int' to 'void *'
ShowMessage(szBuffer);