sprintf(string,"%f",num);
string是一個字符串,num是你要的數字,這樣就能將浮點數num轉成字符串string了,你那個寫法是錯的,后面還有對指針進行運算也是不對的。
char s[20];
int a=10;
sprintf(s,"%d.jpg",a);
//若a=10,則字符串s中存放的是"10.jpg".
C語言在字符串處理中本來就很繁瑣,但字符串處理是編寫代碼最常遇到的問題,今天說的sprintf是printf的加強版。用好了它
能在字符串處理中做到事半功倍的效果,具體看代碼:
函數簡介:
字串格式化命令,主要功能是把格式化的數據寫入某個字符串中。sprintf 是個變參函數,使用時經常出問題,而且只要出問題通常就是能導致程序崩潰的內存訪問錯誤,但好在由sprintf 誤用導致的問題雖然嚴重,卻很容易找出,無非就是那么幾種情況,通常用眼睛再把出錯的代碼多看幾眼就看出來了。
函數功能:
把格式化的數據寫入某個字符串緩沖區。
頭文件:
函數原型:
int sprintf( char *buffer, const char *format, [ argument] … );
參數列表:
buffer:char型指針,指向將要寫入的字符串的緩沖區。
format:char型指針,指向的內存里面存放的將要格式字符串。
[argument]...:可選參數,可以是任何類型的數據。
返回值:字符串長度(strlen)
相關函數:
int sprintf_s(char *buffer,size_t sizeOfBuffer,const char *format, [argument] ... );
int _sprintf_s_l(char *buffer,size_t sizeOfBuffer,const char *format,locale_t locale ,[argument] ... );
int swprintf_s(wchar_t *buffer,size_t sizeOfBuffer,const wchar_t *format ,[argument]...);
int _swprintf_s_l(wchar_t *buffer,size_t sizeOfBuffer,const wchar_t *format,locale_t locale ,[argument]…);
template <size_t size>
int sprintf_s(char (&buffer)[size],const char *format, [argument] ... ); //僅存在於C++
template <size_t size>
int swprintf_s(wchar_t (&buffer)[size],const wchar_t *format ,[argument]...); //僅存在於C++
參數說明及應用舉例
sprintf格式的規格如下所示。[]中的部分是可選的。
%[指定參數][標識符][寬度][.精度]指示符
若想輸出`%'本身時, 請這樣`%%'處理。
1. 處理字符方向。負號時表示從后向前處理。
2. 填空字元。 0 的話表示空格填 0;空格是內定值,表示空格就放着。
3. 字符總寬度。為最小寬度。
4. 精確度。指在小數點后的浮點數位數。
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
轉換字符
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
%% 印出百分比符號,不轉換。
%c 整數轉成對應的 ASCII 字元。
%d 整數轉成十進位。
%f 倍精確度數字轉成浮點數。
%o 整數轉成八進位。
%s 整數轉成字符串。
%x 整數轉成小寫十六進位。
%X 整數轉成大寫十六進位。
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- char buf[100] = "";
- //一、整型格式化為字符串(大多數情況下可以由itoa代替)
- sprintf(buf, "%d", 123);
- puts(buf);
- /*output: 123*/
- //指定寬度,不足的左邊補空格
- strcpy(buf, "");
- sprintf(buf,"%8d%8d", 12,78995);
- puts(buf);
- /*output: 12 78995("12"前面有6個空格,"78995"前邊3個空格)*/
- //十進制左邊對齊輸出
- strcpy(buf, "");
- sprintf(buf, "%-8d%-8d", 456, 84569);
- puts(buf);
- /*output:456 84569(中間5個空格)*/
- //按照16進制打印
- strcpy(buf, "");
- sprintf(buf, "%8x", 4578);
- puts(buf);
- /*output: 12e2*/
- //按照16進制左邊補零輸出
- strcpy(buf, "");
- sprintf(buf, "%08X", 4569);
- puts(buf);
- /*output: 000011D9*/
- //左邊補零方式打印一個短整型
- strcpy(buf, "");
- sprintf(buf, "%04X", (unsigned short)2);
- puts(buf);
- /*output: 0002*/
- //二、浮點型打印成字符串
- strcpy(buf, "");
- sprintf(buf, "%f", 3.1415926);
- puts(buf);
- /*output: 3.141593 四舍五入*/
- //控制寬度和小數點位數輸出
- strcpy(buf, "");
- sprintf(buf, "%10.3f", 3.1415926);
- puts(buf);
- /*output: 3.142(前面5個空格)*/
- //連接字符串
- strcpy(buf, "");
- char buf1[]="I"; char buf2[]="you!";
- sprintf(buf, "%s love %s", buf1, buf2);
- puts(buf);
- /*output: I love you!*/
- //連接2個字符串沒有以'\0'結束
- //sprintf 采用”*”來占用一個本來需要一個指定寬度或精度的常數數字的位置
- strcpy(buf, "");
- char a1[] = {'a', 'b', 'c', 'd', 'e'};
- char a2[] = {'f', 'g', 'h', 'j'};
- //sprintf(buf, "%s%s", a1, a2); //error
- //sprintf(buf, "%5s%4s", a1, a2); //error
- //sprintf(buf, "%.5s%.4s", a1, a2); //method one
- //sprintf(buf, "%.*s%.*s", 5, a1, 4, a2); //method two
- sprintf(buf, "%.*s%.*s", sizeof(a1), a1, sizeof(a2), a2); //method three
- puts(buf);
- return 0;
- }
頭文件:#include <stdio.h>
sprintf()函數用於將格式化的數據寫入字符串,其原型為:
int sprintf(char *str, char * format [, argument, ...]);
【參數】str為要寫入的字符串;format為格式化字符串,與printf()函數相同;argument為變量。
除了前兩個參數類型固定外,后面可以接任意多個參數。而它的精華,顯然就在第二個參數--格式化字符串--上。 printf()和sprintf()都使用格式化字符串來指定串的格式,在格式串內部使用一些以“%”開頭的格式說明符(format specifications)來占據一個位置,在后邊的變參列表中提供相應的變量,最終函數就會用相應位置的變量來替代那個說明符,產生一個調用者想要的字符串。
sprintf()最常見的應用之一莫過於把整數打印到字符串中,如:
sprintf(s, "%d", 123); //把整數123打印成一個字符串保存在s中
sprintf(s, "%8x", 4567); //小寫16進制,寬度占8個位置,右對齊
sprintf的作用是將一個格式化的字符串輸出到一個目的字符串中,而printf是將一個格式化的字符串輸出到屏幕。sprintf的第一個參數應該是目的字符串,如果不指定這個參數,執行過程中出現 "該程序產生非法操作,即將被關閉...."的提示。
sprintf()會根據參數format 字符串來轉換並格式化數據,然后將結果復制到參數str 所指的字符串數組,直到出現字符串結束('\0')為止。關於參數format 字符串的格式請參考printf()。
【返回值】成功則返回參數str 字符串長度,失敗則返回-1,錯誤原因存於errno 中。
注意:C語言對數組進行操作時並不檢測數組的長度,如果str的長度不夠,sprintf()很容易造成緩沖區溢出,帶來意想不到的后果,黑客經常利用這個弱點攻擊看上去安全的系統。請看下面的代碼:
- #include <stdio.h>
- main()
- {
- char buf[10];
- sprintf(buf, "The length of the string is more than 10");
- printf("%s", buf);
- }
編譯並運行,屏幕上輸出”The length of the string is more than 10“,同時系統提示程序已經停止。原因就是要寫入的字符串的長度超過了buf的長度,造成緩沖區溢出。
使用snprintf()來代替sprintf()將能夠很好的解決這個問題。
【實例】打印字母a的ASCII值。
- #include <stdio.h>
- main()
- {
- char a = 'a';
- char buf[80];
- sprintf(buf, "The ASCII code of a is %d.", a);
- printf("%s", buf);
- }
運行結果:
The ASCII code of a is 97.
又如,產生10個100以內的隨機數並輸出。
- #include<stdio.h>
- #include<stdlib.h>
- #include<time.h>
- int main(void)
- {
- char str[100];
- int offset =0;
- int i=0;
- srand(time(0)); // *隨機種子
- for(i = 0;i<10;i++)
- {
- offset+=sprintf(str+offset,"%d,",rand()%100); // 格式化的數據寫入字符串
- }
- str[offset-1]='\n';
- printf(str);
- return 0;
- }
運行結果:
74,43,95,95,44,90,70,23,66,84
例子使用了一個新函數srand(),它能產生隨機數。例子中最復雜的部分是for循環中每次調用函數sprintf()往字符數組寫數據的時候,str+foffset為每次寫入數據的開始地址,最終的結果是所有產生的隨機數據都被以整數的形式存入數組中。
sprintf
Converts floats or doubles into formatted strings.
Prototype
function sprintf ( format [1] : string, array : float ; or double ) return_val [dimsizes(array)] : string
Arguments
formatA "C" style format string, See "man sprintf" for more information.
arrayAn array of any dimensionality of float or double values.
Description
This function uses the format string to call the system "sprintf" function. This is different from the C version in two ways: 1) only one "%" operator is allowed for the string, and 2) only floating point numbers (float and double) are allowed. You must understand how to create a C format string to use this function.
Briefly, the applicable conversion characters for printing are:
- Each conversion specification begins with a % and ends with a conversion character: f, e/E, g/G.
- Between the % and the conversion character, there may be, in order:
- A minus sign, which specifies left adjustment of the converted argument.
- A number that specifies the minimum field width. The converted argument will be printed in a field at least this wide. It will be padded if necessary.
- A period, which separates the field width from the precision.
- A number, the precision, that specifies the maximum number of characters to be printed from a string, or the number of digits after the decimal point of a floating point value.
- A minus sign, which specifies left adjustment of the converted argument.
- Conversion characters are:
f: [-]m.dddddd, where the number of d's is given by the precision (default 6).
e[,E]: [-]m.dddddde±xx or [-]m.ddddddE±xx, where the number of d's is given by the precision (default 6).
g[,G]: use %e or %E if the exponent is less than -4 or greater than or equal to the precision; otherwise use %f.
See Also
Examples
Example 1
The code snippet:
x = 12.3456
title = "Sample title, x=" + sprintf("%5.2f", x)
will result in title = "Sample title, x=12.35". Note that the value returned by sprintf is rounded, due to the specified print format.
Example 2
Here are some additional examples demonstrating the "e[,E]" and "g[,G]" formats:
x = 12.3456 print( sprintf("%7.3e", x) ) ===> 1.235e+01
x = -0.000013583 print( sprintf("%4.3E", x) ) ===> -1.358E-05
x = 23456789. print( sprintf("%6.4g", x) ) ===> 2.3457e+07
print( sprintf("%6.4G", 10000000.) ) ===> 1E+07
print( sprintf("%6.4g", 10.) ) ===> 10
print( sprintf("%6.4g", 10.56) ) ===> 10.56
Example 3
A user could also put the format into a string variable:
fmt = "%5.2f"
emt = "%7.3e"
gmt = "%4.3g"
title = "Sample title, x=" + sprintf(fmt, x) +" y="+ sprintf(fmt, y) \
+" z=" + sprintf(gmt, z)
subTitle = sprintf(gmt, x)
Example 4
sprinti and sprintf can be used to provide limited formatting for printing ASCII text. The following code:
print(" K mylats mylons exacts mytemps fo") do n=0,N-1 print (sprinti("%6.0i", knt(n)) +" " \ +sprintf("%9.5f", mylats(n)) +" " \ +sprintf("%9.2f", mylons(n)) +" " \ +sprintf("%9.3f", exacts(n)) +" " \ +sprintf("%9.4f", mytemps(n))+" " \ +sprintf("%9.4f", fo(n)) ) end do
will produce the following output:
(0) K mylats mylons exacts mytemps fo (0) 16.28100 -126.14 20.650 20.6500 20.6500 (0) 5 16.28110 -126.14 20.650 20.6500 -999.0000 (0) 25 16.36279 -125.77 20.550 20.5500 20.5500 (0) 50 16.36289 -125.77 20.550 20.4501 20.4501 (0) 75 16.71504 -125.86 20.350 20.3500 20.3500 (0) 100 16.71514 -125.86 20.350 20.3501 20.3502 (0) 300 16.63296 -126.22 20.650 20.6500 20.6500 (0) 400 16.63305 -126.22 20.650 20.6500 -999.0000 (0) 700 40.57919 -74.57 2.350 2.3500 2.3500 (0) 900 40.57929 -74.57 2.350 3.4908 3.4891 (0) 1000 40.52584 -74.11 4.750 4.7500 4.7500 (0) 3000 40.52594 -74.11 4.750 4.5151 4.5153 (0) 7000 40.87282 -74.04 1.350 1.3500 1.3500 (0) 10000 40.87292 -74.04 1.350 2.2145 2.2143 (0) 15000 40.92625 -74.50 0.850 0.8500 0.8500 (0) 123456 40.92635 -74.50 0.850 1.4571 1.4570
