2、 其他數(shù)據(jù)類型轉(zhuǎn)換為字符串
2.1 int轉(zhuǎn)換為字符串
把“整數(shù)”轉(zhuǎn)換為“字符串”的函數(shù)有:
_itoa(……)轉(zhuǎn)換整型數(shù)據(jù),
_i64toa(……)轉(zhuǎn)換64位整型數(shù)據(jù),
_ui64toa(……)轉(zhuǎn)換無符號(hào)64位整型數(shù)據(jù),
_itow(……),_i64tow(……),_ui64tow(……)。
函數(shù)的原型如下:
char *_itoa(
int value,
char *string,
int radix
);
char *_i64toa(
_int64 value,
char *string,
int radix
);
char *_ui64toa(
unsigned _int64 value,
char *string,
int radix
);
wchar_t *_itow(
int value,
wchar_t *string,
int radix
);
wchar_t *_i64tow(
_int64 value,
wchar_t *string,
int radix
);
wchar_t *ui64tow(
unsigned _int64 value,
wchar_t *string,
int radix
);
參數(shù)的意義:value是指要轉(zhuǎn)換的整數(shù),string是用來存放轉(zhuǎn)換后結(jié)果的變量,radix是用來說明轉(zhuǎn)換成幾進(jìn)制的數(shù)據(jù),默認(rèn)值是十進(jìn)制數(shù)的。轉(zhuǎn)換的進(jìn)制范圍是二進(jìn)制到三十六進(jìn)制。
實(shí)例代碼:
#include"stdafx.h"
#include<stdlib.h>
#include<iostream>
using namespace std;
int main(int argc, char* argv[])


{
int iii=123456789;
char ii[12];
itoa(iii,ii,10);//int轉(zhuǎn)換為字符串,十進(jìn)制
int i;
for(i=0;i<=12;i++)


{
cout<<"ii["<<i<<"]="<<ii[i]<<endl;
}

int iii2=12;
char ii2[6];
itoa(iii2,ii2,2);//int轉(zhuǎn)換為字符串,二進(jìn)制
for(i=0;i<=6;i++)


{
cout<<"ii2["<<i<<"]="<<ii2[i]<<endl;
}
return 0;
}

2.2 long轉(zhuǎn)換為字符串
long是轉(zhuǎn)換字符串函數(shù),系統(tǒng)函數(shù)庫(kù)為此提供了函數(shù)_ltoa, _ltow。其函數(shù)原型如下:
char *_ltoa(long value, char *string, int radix);
wchar_t *_ltow(long value, wchar_t *string, int radix);
其中,參數(shù)value為被轉(zhuǎn)換的值,參數(shù)string為字符串緩沖區(qū),radix為進(jìn)制。
代碼參考如下:
#include"stdafx.h"
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
int main(int argc, char* argv[])


{
long l_num=100;char temp[10];

/**//********************/

/**//*void *memset(void *s,int c,size_t n)
/*總的作用:將已開辟內(nèi)存空間 s 的首 n 個(gè)字節(jié)的值設(shè)為值 c。
/*#include<string.h>
/********************/
memset(temp,0,10);
ltoa(l_num,temp,10);//#include<stdlib.h>里面
for(int i=0;i<=10;i++)


{
cout<<"temp["<<i<<"]="<<temp[i]<<endl;
}
return 0;
}
2.3 double轉(zhuǎn)換為字符串
float轉(zhuǎn)換字符串,系統(tǒng)提供了函數(shù)_fcvt來實(shí)現(xiàn)這個(gè)功能,其函數(shù)原型如下:
char *_fcvt(double value, int count, int *dec, int *sign);
其中參數(shù)value為雙精度數(shù),參數(shù)count為轉(zhuǎn)換的小數(shù)點(diǎn)后面的位數(shù),dec表示小數(shù)點(diǎn)的位置,sign表示符號(hào)。代碼參數(shù)如下:
#include "stdafx.h"
#include<stdlib.h>
#include<iostream>
using namespace std;
int main(int argc, char* argv[])


{
int decimal,sign;
char *buffer;
double source=3.1415926535;
buffer=_fcvt(source,7,&decimal,&sign);
cout<<"source="<<source<<endl;//cout默認(rèn)輸出浮點(diǎn)數(shù)的前六位
cout<<"buffer="<<buffer<<endl;
cout<<"decimal="<<decimal<<endl;
cout<<"sign="<<sign<<endl;
return 0;
}
2.4 日期類型轉(zhuǎn)換為字符串
將以日期格式轉(zhuǎn)換為字符串,利用了格式化函數(shù),參考代碼如下
還有,整理一下與日期相關(guān)的操作,也就是time.h的,其隨筆地址如下:
http://m.shnenglu.com/kangnixi/archive/2010/01/27/106555.html
如果還想獲得更多關(guān)于《Visual C++代碼參考與技巧大全》的內(nèi)容,可點(diǎn)擊下面網(wǎng)址,
http://m.shnenglu.com/kangnixi/archive/2010/01/13/105591.html