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

1
2
3
4
5
6
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
2
3
4
// 1
string str="hello";
const char* p=str.data();
char* p=(char*)str.data();

 

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

 

1
2
3
4
5
6
7
8
9
// 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

1
2
3
4
5
6
7
8
9
10
11
12
13
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 @   言午丶  阅读(275)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示