2、 其他數據類型轉換為字符串
2.1 int轉換為字符串
把“整數”轉換為“字符串”的函數有:
_itoa(……)轉換整型數據,
_i64toa(……)轉換64位整型數據,
_ui64toa(……)轉換無符號64位整型數據,
_itow(……),_i64tow(……),_ui64tow(……)。
函數的原型如下:
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
);
參數的意義:value是指要轉換的整數,string是用來存放轉換后結果的變量,radix是用來說明轉換成幾進制的數據,默認值是十進制數的。轉換的進制范圍是二進制到三十六進制。
實例代碼:
#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轉換為字符串,十進制
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轉換為字符串,二進制
for(i=0;i<=6;i++)


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

2.2 long轉換為字符串
long是轉換字符串函數,系統函數庫為此提供了函數_ltoa, _ltow。其函數原型如下:
char *_ltoa(long value, char *string, int radix);
wchar_t *_ltow(long value, wchar_t *string, int radix);
其中,參數value為被轉換的值,參數string為字符串緩沖區,radix為進制。
代碼參考如下:
#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)
/*總的作用:將已開辟內存空間 s 的首 n 個字節的值設為值 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轉換為字符串
float轉換字符串,系統提供了函數_fcvt來實現這個功能,其函數原型如下:
char *_fcvt(double value, int count, int *dec, int *sign);
其中參數value為雙精度數,參數count為轉換的小數點后面的位數,dec表示小數點的位置,sign表示符號。代碼參數如下:
#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默認輸出浮點數的前六位
cout<<"buffer="<<buffer<<endl;
cout<<"decimal="<<decimal<<endl;
cout<<"sign="<<sign<<endl;
return 0;
}
2.4 日期類型轉換為字符串
將以日期格式轉換為字符串,利用了格式化函數,參考代碼如下
還有,整理一下與日期相關的操作,也就是time.h的,其隨筆地址如下:
http://www.shnenglu.com/kangnixi/archive/2010/01/27/106555.html
如果還想獲得更多關于《Visual C++代碼參考與技巧大全》的內容,可點擊下面網址,
http://www.shnenglu.com/kangnixi/archive/2010/01/13/105591.html