C89:论各种类型相互转换

一.int

1.int转float

 

2.int转double

 

3.int转string

 

4.int转char*

 

二.float

1.float转int

 

2.float转double

 

3.float转string

 

4.float转char*

 

三.double

1.double转int

 

2.double转float

 

3.double转string

 

4.double转char*

 

四.char* / char[]

1.char*转int

 

2.char*转float

 

3.char*转double

 

4.char* / char[]转string

string s;
char* p="hello";
char a[]="hello";
 
s=p;
s=a;

 

 

五.string

1.string转int

 

2.string转float

 

3.string转double

 

4.string转char* / char[]

// 1
string str="hello";
const char* p=str.data();
char* p=(char*)str.data();

 

// 2
string str="world";
const char* p=str.c_str();
char* p=(char*)str.c_str();

 

// 3
string str="test";
char array[50];
str.copy(array,48,0);  //48代表数组长度,0代表起始位置
array[49]='\0';        //添加结束符
 
char* p=new char[50]();
str.copy(p,48,0);
*(p+49)='\0';

 

六.LPCWSTR

1.LPCWSTR转string

std::string Wchar2Ansi(LPCWSTR pwszSrc)
{
    int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL);
    if (nLen <= 0)  return std::string("");
    char* pszDst = new char[nLen];
    if (NULL == pszDst)  return std::string("");
    WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL);
    pszDst[nLen -1] =0;
    std::string strTemp(pszDst);
    delete[]  pszDst;

    return strTemp;      
}

 

posted @ 2019-06-26 15:04  言午丶  阅读(266)  评论(0编辑  收藏  举报