CString類常用方法----Format(),sprintf(),itoa(),ltoa(),ultoa(),atoi(),atol(),atof()

void Format( LPCTSTR lpszFormat, ... );和printf的使方法一樣

void Format( UINT nFormatID, ... );利用資源格式化字符串,這個比上面的省空間,方便改,功能一樣

作用:像printf一樣格式化字符串

 

int sprintf( char *buffer, const char *format [, argument] ... );//用法和 printf 一樣

 

char *itoa( int value, char *string, int radix );

注:

   參數:int value :是要轉爲字符串的int型

          char *string :存放字符串的緩衝區

          int radix  :將int轉換爲多少進制的數存放在緩衝區中 

 

char *ltoa( long value, char *string, int radix );

注:

   參數:long value :是要轉爲字符串的long

          char *string :存放字符串的緩衝區

          int radix  :將long轉換爲多少進制的數存放在緩衝區中 

 

char *ultoa( unsigned long value, char *string, int radix );

注:

   參數:unsigned long value :是要轉爲字符串的unsigned long型

          char *string :存放字符串的緩衝區

          int radix  :將unsigned long轉換爲多少進制的數存放在緩衝區中 

 

int atoi( const char *string );

注:

   參數:const char *string :是要轉爲int型的字符串

   返回值:字符串對應的int型

long atol( const char *string );

注:

   參數:const char *string :是要轉爲long型的字符串

   返回值:字符串對應的long型

double atof( const char *string );

注:

   參數:const char *string :是要轉爲double型的字符串

   返回值:字符串對應的double型

例:

1.void Format( LPCTSTR lpszFormat, ... );

 

CString a,b;
a = "12卡拉";

b.Format("%s", a);                       // b的值爲"12卡拉";,因爲是把a格式化到b中,相當於a=b
b.Format("%d", a.GetLength());   // b的值爲6,因爲是把a的字節長格式化到b中

 


2.void Format( UINT nFormatID, ... );

(1)先打開"ResourceView"視窗

(2)點開"String Table"

(3)雙擊"String Table [English [U.S.]]"

(4)右鍵右邊的下邊空白,點"New String"

(5)在"Caption"右邊的框中添:%d(這裏也可以改成%s,%c等,根據須要來決定)

(6)把上面的"ID"記住

 

CString a,b;
a = "12卡拉";
b.Format(添上面的ID號, a.GetLength());   // b的值爲6,因爲是把a的字節長格式化到b中

 

例2:

 

char *p = new char[255];
 int a = 10;
 double b = 3.14;
 long c = 20;
 unsigned d = 30;
 char *e = "abcde";
 CString f;

 sprintf(p, "%d", a);   //p中的值爲10
 sprintf(p, "%lf", b);  //p中的值爲3.140000
 sprintf(p, "%ld", c);  //p中的值爲20
 sprintf(p, "%u", d);   //p中的值爲30
 sprintf(p, "%s", e);   //p中的值爲abcde

 f.Format("%d", a);   //f中的值爲10
 f.Format("%lf", b);  //f中的值爲3.140000
 f.Format("%ld", c);  //f中的值爲20
 f.Format("%u", d);   //f中的值爲30
 f.Format("%s", e);   //f中的值爲abcde

 itoa(a, p, 10);      //p中的值爲10
 ltoa(c, p, 10);      //p中的值爲20
 ultoa(d, p, 10);     //p中的值爲30

 char *g = "40";
 char *h = "4.59";
 int i = atoi(g);     //i中的值爲40
 long j = atol(g);    //j中的值爲40
 double k = atof(h);  //k中的值爲4.58999999...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章