字元與數字的轉換:sprintf和sscanf
阿新 • • 發佈:2018-11-02
目錄
字元與數字的轉換:sprintf和sscanf
簡單介紹
sprintf和sscanf都是stdio.h標頭檔案中的函式,請大家放心使用~
其中,sprintf可以將任意數字包括小數點(.)和負號(-)轉換成字串(這裡指的char陣列)
而sscanf則負責將字串轉化為任意型別的數字。
例項
#include <stdio.h> #include <string.h> int main(){ char a[100],e[100]="-"; int b=132,c=168; sprintf(a,"%d.%d",b,c); double d; strcpy(e+1,a); sscanf(e,"%lf",&d); printf("%s\n%lf",a,d); return 0; }
可以看到,在上面的例項中,
- 我先使用sprintf將整型的b和c以及一個小數點(.)組合之後轉化成字串。(這個功能超強的啊)
- 然後用strcpy將e賦值成多了一個負號(-)的a。
- 再通過sscanf將浮點型別的d賦值上字元陣列e的值。
- 最後輸出a和d。