分享

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

 孤独求学者 2012-06-29
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...

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多