首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

char[]转为string,该如何解决

2012-03-19 
char[]转为string#includestring#includeiostream#includestdio.husingnamespacestdvoidDeciToBin(

char[]转为string
#include   <string>
#include   <iostream>
#include   <stdio.h>

using   namespace   std;
void   DeciToBin(short   decimal,char   bintemp[]);
int   main()
{
short   d   =   30043;
char   bintemp[16];
char   a[5]= "abc ";
DeciToBin(d,bintemp);

string       str   =   bintemp;      

cout < <str < <endl;

return   0;
}
void   DeciToBin(short   decimal,char   bintemp[])
{
int   count   =   15;

for(int   i=0;i <16;i++)
bintemp[i]   =   0;

while(decimal> 0)
{
bintemp[count]=decimal%2;
decimal=decimal/2;
count--;
}
}
为什么str   =   a;输出的就是abc,str   =   bintemp输出就为空?
我该如何将bintemp转换成str(转换过程中,不能用itoa函数)

[解决办法]
#include "string "
#include "iostream "
#include "stdio.h "
#include "math.h "
using namespace std;
int DeciToBin(int decimal, double *bintemp);
int main()
{
int d = 30043;
char *bintemp;
double bin = 0;
int binLen = DeciToBin(d, &bin);
bintemp = (char *)malloc(binLen + 128);
memset(bintemp, 0 , binLen + 128);
for(int i =0; i < binLen; i++)
{
double exp = pow(10.0, binLen -1 -i);
int tmpBin = (int)(bin/exp);
bin -= (double)tmpBin * exp;
bintemp[i] = tmpBin + '0 ';
}
string str = bintemp;
cout < <str < <endl;
free(bintemp);
return 0;
}
int DeciToBin(int decimal, double *bintemp)
{
int count = 0;
double exp;
if (_set_SSE2_enable(1))
printf( "SSE2 enabled.\n ");
else
printf( "SSE2 not enabled; processor does not support SSE2.\n ");

while(decimal> 0)
{
exp = pow(10.0, count);
*bintemp +=((decimal%2) *exp);
decimal = decimal/2;
count++;
}
return count;
}


----------------------------
给分

热点排行