C++字符串和數字格式轉化(使用sprintf()和sscanf()函數)


本文參考摘抄整理自:http://www.cnblogs.com/luxiaoxun/archive/2012/08/03/2621803.html

 1 #include<stdio.h>
 2 #include<iostream>
 3 using namespace std;
 4 int main(){
 5     
 6     //--------------數字轉字符串,使用sprintf(char數組名,類型,數字變量名) 
 7     //整數轉十進制字符串
 8     char str[10];
 9     int a=1234321;
10     sprintf(str,"%d",a);
11     
12     //小數轉十進制字符串 
13     char str1[10];
14     double b=123.321;
15     sprintf(str1,"%.3lf",b);
16     //十進制整數轉十六進制字符串
17     char str2[10];
18     int c=175;
19     sprintf(str2,"%x",c);
20     cout<<"數字-->字符串:"<<endl;
21     cout<<str<<endl<<str1<<endl<<str2<<endl;
22     
23     //----------------字符串轉數字,使用sscanf()函數
24     //字符串轉整數 
25     char str3[]="1234321";
26     int d;
27     sscanf(str3,"%d",&d); 
28     
29     //字符串轉小數
30     char str4[]="123.321";
31     double e;
32     sscanf(str4,"%lf",&e);
33     //十六進制字符串轉十進制整數
34     char str5[]="AF";
35     int f;
36     sscanf(str5,"%x",&f); 
37     
38     cout<<"字符串-->數字:"<<endl;
39     cout<<d<<endl<<e<<endl<<f<<endl;
40 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM