---
title: "string, char*, int类型转换  , c++强制转化"
author: "sealbird"
date: "2011-01-10T10:04:15Z"
tags: ["C", "C#", "C++", "MFC", "VC++"]
categories: ["编程语言"]
slug: "string-char-int-c"
draft: false
lastmod: "2011-01-10T16:28:41Z"
id: 866701
url: "https://sealbird.iteye.com/blog/866701"
---

**一、**

```
以下是常用的几种类型互相之间的转换
string 转 int
..............................
char* 转 int 
#include <stdlib.h> 

int atoi(const char *nptr); 
long atol(const char *nptr); 
long long atoll(const char *nptr); 
long long atoq(const char *nptr); 
...................................................................
int 转 string 
可以使用stringstream类(需要包含<sstream>头文件)
int main()
{
   stringstream ss;
   int i = 100;
   string str;
   ss >> i;
   ss << str; //这时str中就是字符串"100".
   retturn 0;
}

.............................
char* 转 string  
string s(char *);  
你的只能初始化，在不是初始化的地方最好还是用assign().
..................................................................
int 转 char *
在stdlib.h中有个函数itoa() 
itoa的用法： 
itoa(i,num,10); 
i 需要转换成字符的数字 
num 转换后保存字符的变量 
10 转换数字的基数（进制）10就是说按照10进制转换数字。
还可以是2，8，16等等你喜欢的进制类型 
原形：char *itoa(int value, char* string, int radix); 

实例： 
#include "stdlib.h" 
#include "stdio.h" 
main() 
{ 
    int i=1234; 
    char s[5]; 
    itoa(i,s,10); 
    printf("%s",s); 
    getchar(); 
}
..........................................
string 转 char *  
char *p = string.c_str();  

string aa("aaa"); 
char *c=aa.c_str(); 
string mngName； 
char t[200]; 
memset(t,0,200); 
strcpy(t,mngName.c_str());
.......................................... 


posted on 2008-04-17 15:22 林公子 阅读(8479) 评论(3)  编辑 收藏 引用 所属分类: C++/CLI 
 


评论
# re: [转]string, char*, int类型转换 2009-01-29 16:51 ChriHan 
string str; 
ss >> i; 
ss << str; //这时str中就是字符串"100". 

这个部分好像不对， 
应该是 
ss << i; 这时str中就是字符串"100". 
可以通过ss.str()提取ss中的内容  回复  更多评论 
   


# re: [转]string, char*, int类型转换 2009-02-02 13:57 erosnick 
@ChriHan 
谢谢Chrihan的更正，以后得注意点, 避免bug:)  回复  更多评论 
   


# re: [转]string, char*, int类型转换 2009-07-06 13:17 Robert.Hu 
在"string 转 char * "中

"char *c=aa.c_str();"
错了吧，c_str()返回的是const char* 而 const char* 不能转换成char*  回复  更多评论 
   
```

二、  
c++ int转换成string类型 代码

//第一种方法

```
 #include <iostream>
#include <string>
using namespace std;

int main()
{
    int n = 65535;
    char t[256];
    string s;

    sprintf(t, "%d", n);
    s = t;
    cout << s << endl;

    return 0;
}
```

    //第二种方法

```
#include <iostream>
#include <string>
#include <strstream>
using namespace std;

int main()
{
    int n = 65535;
    strstream ss;
    string s;
    ss << n;
    ss >> s;
    cout << s << endl;

    return 0;
}
```

三、

引用

最近做项目用到c++，才发现c++中的数据类型不是一般的BT。尤其是我和婷还是分开操作的。我写底层，用的是WIN32控制台；而婷写MFC。由于没有经验，所以没有写中间的转换程序。当集成时，类型转换特别麻烦。以下都是我收集的类型转换的方法和一些经验，供大家参考。欢迎补充~~

1\. char* to string  
string s(char \*);   
注：在不是初始化的地方最好用assign().  
！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！  
2\. string to const char*  
string a="strte";  
const char* r=a.c\_str();  
注意是const的。还要转到char\*：  
\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  
2.2. const char* to char*  
const char* r="123";  
char   \*p1   =   new   char\[strlen(r)+1];  
strcpy(p1,r);  
附：http://hi.baidu.com/cfans/blog/item/06970ef4b671f366dcc4745d.html  
这个页面是具体讲述区别的。  
·············································································································  
3\. cstring to string  
vs2005 Unicode下：  
  CStringW   str(L"test");    
  CStringA   stra(str.GetBuffer(0));    
  str.ReleaseBuffer();        
  std::string   strs   (stra.GetBuffer(0));    
  stra.ReleaseBuffer();

非Unicode下：  
CString cs("test");  
std::string str=cs.getBuffer(0);  
cs.ReleaseBuffer();

注：GetBuffer()后一定要ReleaseBuffer(),否则就没有释放缓冲区所占的空间.  
++++++++++++++++++++++++++++++++++++++++++++++++++++  
4\. double ,int to string  
#include &lt;sstream&gt;  
using namespace std;

stringstream ss;  
string result;  
long n=11111;  
stream &lt;&lt; n; //从long型数据输入  
stream &gt;&gt;result; //转换为 string

===================================================

5.char*  to int, double ,long

char \*s; double x; int i; long l;

s = " -2309.12E-15"; /* Test of atof \*/  
x = atof( s );  
printf( "atof test: ASCII string: %s\\tfloat: %e\\n", s, x );

s = "7.8912654773d210"; /* Test of atof \*/  
x = atof( s );  
printf( "atof test: ASCII string: %s\\tfloat: %e\\n", s, x );

s = " -9885 pigs"; /* Test of atoi \*/  
i = atoi( s );  
printf( "atoi test: ASCII string: %s\\t\\tinteger: %d\\n", s, i );

s = "98854 dollars"; /* Test of atol \*/  
l = atol( s );  
printf( "atol test: ASCII string: %s\\t\\tlong: %ld\\n", s, l );  
\------------------------------------------------------------------------------------------------  
6\. string to int ,long ,double              
              int s;  
string str="123";  
stringstream ss;  
ss&lt;&lt;str;//从str输入  
ss&gt;&gt;s;//输出到int  
ss.clear();

——————————————————————————————————————————  
7\. date to string  
#include &lt;time&gt;  
using namespace std;

char dateStr \[9];  
char timeStr \[9];  
\_strdate( dateStr);  
printf( "The current date is %s \\n", dateStr);  
\_strtime( timeStr );  
printf( "The current time is %s \\n", timeStr);

--------实践证明是正确的版本--------------------------------------------------------------  
#include &lt;iostream&gt;  
#include &lt;ctime&gt;  
#include &lt;cerrno&gt;

int main()  
{  
     //Find the current time  
     time\_t curtime = time(0);  
       
      //convert it to tm  
      tm now=\*localtime(&curtime);  
      
     //BUFSIZ is standard macro that expands to a integer constant expression  
     //that is greater then or equal to 256. It is the size of the stream buffer  
     //used by setbuf()  
     char dest\[BUFSIZ]={0};  
      
     //Format string determines the conversion specification's behaviour  
     const char format\[]="%A, %B %d %Y. The time is %X";  
      
     //strftime - converts date and time to a string  
     if (strftime(dest, sizeof(dest)-1, format, &now)&gt;0)  
       std::cout&lt;&lt;dest&lt;&lt;std::endl;  
     else  
       std::cerr&lt;&lt;"strftime failed. Errno code: "&lt;&lt;errno&lt;&lt;std::endl;  
}

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||  
8.string to cstring

+++++++++++++++++++++++++++++++++++++++++++++++++++++  
非Unicode下：  
int 转 CString：  
CString.Format("%d",int);  
...............................  
string 转 CString   
CString.format("%s", string.c\_str());   
用c\_str()确实比data()要好.   
.......................................  
char* 转 CString   
CString.format("%s", char\*);   
CString strtest;   
char * charpoint;   
charpoint="give string a value";   
strtest=charpoint; //直接付值  
.....................................................  
CString 转 int  
CString  ss="1212.12";   
int temp=atoi(ss); //atoi \_atoi64或atol  
...................................................................................................................................  
9.在Unicode下的CString to double  
CSting sTemp("123.567");  
double dTemp = \_wtof(sTemp.GetString());

文章出处：飞诺网(www.firnow.com):http://dev.firnow.com/course/3\_program/c++/cppjs/20090412/164832.html

4、  
收藏  
强制转化四种类型可能很多人都常常忽略就象我一样，但是有时还是比较有用的。不了解的建议看看，一些机制我也不是十分了解，只是将一些用法写出来让大家看看。  
                                                            2004-11-27 9:00

强制转化无论从语法还是语意上看，都是c++中最难看的特征之一。但是基于c风格的转化的语义的不明确性及其一些潜在问题。强制类型转化最终还是被c++接受了。  
1.static\_cast运算符号  
static\_cast&lt;T&gt;(e),stroustrup让我们可以把它看成隐含转换的显示的逆运算。这个是有一定道理的，基于隐式转化的对象类型我们可以使用static\_cast转化运算符号。它是静态的检测，无法运行时检测类型，在继承中尤为突出。  
使用范围  
&lt;1&gt;用于所有系统类型之间转化，不能用于系统类型指针类型转化

```
  double t_d = 0;
int t_i= static_cast<int>(t_d); //是合法的转化
```

而企图将double\*-&gt;int\*是不允许的  
&lt;2&gt;用于继承类之间的转化（含指针），不能用于其他没有隐式转化的对象类型之间的转化  
继承举例:

```
class x
{
};
class y: public x
{
};
使用:x t_o_x;
y t_o_y = static_cast<y>(t_o_x); //x* y*转化也可以进行因为x,y继承关
//系，类型可以自动隐式转化使用
   隐式转化举例:
class x
{
};
class y
{

public:
    y( x i_x ) {}
};
    x t_o_x;
     y t_o_y = static_cast<y>(t_o_x);
```

//大家看到y构造函数可以对于x类型隐式转化  
//所以可以将x-&gt;y，如果企图将y-&gt;x会报错  
2.reinterpret\_cast 运算  
主要用于对于类型指针类型的强制转化，some\_type* -&gt; special\_type\*这样转化，类型信息可以是不完全的。它允许将任意指针转化到其他类型指针，也允许任意整数类型到任意指针类型转化(BT)。这样导致的结果是极其不安全的，不能安全的应用于其他目的，除非转化到原来类型。  
&lt;1&gt; 使用所有整形可以转化为任意类型的指针(指针是4字节的long的东东，那么机器就认为同类型就是可以转化)

```
int c;
x* p = reinterpret_cast<x*>(c); 
```

//x是自定义的任意类型，当然包括系统类型  
&lt;2&gt; 可以对于任意类型指针之间转化

```
y* c;
x* p = reinterpret_cast<x*>(c);//
```

x,y代表所有自定义或系统类型  
大家可以看到reinterpret\_cast的转化是极度的不负责任的，他只管转化不检测是否可以转化。  
&lt;3&gt; const\_cast运算符号  
这个很简单从名字大家可以看出来，仅仅为了去掉或着加上const修饰符号。但是对于本身定义时为const的类型，即使你去掉const性，在你操作这片内容时候也要小心，只能r不能w操作，否则还是会出错。

```
const char* p = "123";
char* c = const_cast<char*>(p);
```

c\[0] = 1;  //表面上通过编译去掉了const性，但是操作其地址时系统依然不允许这  
//么做。这是一个漏洞吧  
&lt;4&gt; dynamic\_cast运算符号  
Scott Mayers将其描述为用来执行继承体系中：安全的向下转型或者跨系转型动作。也就是说你可以，用dynamic\_cast将 指向base class的指针或引用转型为 指向子类的对象的指针或引用。

```
class B {};  //polymorphic类型含virtual才能dynamic_cast
class D: public B {}
void f( B* pb )
{
    D* pd1 = dynamic_cast<D*>(pb);//如果pb为d类型正确返回，如果不是返回0
    D* pd2 = static_cast<D*>(pb);
```

//不管怎么样都返回指针有可能指向不合适的对  
//象，因为static仅仅静态检测，不能得到运  
//行时对象的信息是否真正为D类型  
}

反正大家在使用知道怎么用就ok了，c++强制转化在模板中还是非常有用的，其他时候本人也喜欢用c的转化方便

本文来自CSDN博客，转载请标明出处：http://blog.csdn.net/goodluckyxl/archive/2005/01/19/259851.aspx

**5、static\_cast&lt;&gt;揭密**

```
static_cast<>揭密


作者：Sam NG 

译者：小刀人


原文链接：What static_cast<> is actually doing

本文讨论static_cast<> 和 reinterpret_cast<>。 

介绍
大多程序员在学C++前都学过C，并且习惯于C风格（类型）转换。当写C++（程序）时，有时候我们在使用static_cast<>和reinterpret_cast<>时可能会有点模糊。在本文中，我将说明static_cast<>实际上做了什么，并且指出一些将会导致错误的情况。

泛型（Generic Types）



        float f = 12.3;
        float* pf = &f;
      // static cast<>
        // 成功编译, n = 12
        int n = static_cast<int>(f);
        // 错误,指向的类型是无关的（译注：即指针变量pf是float类型，现在要被转换为int类型）
        //int* pn = static_cast<int*>(pf);
        //成功编译
        void* pv = static_cast<void*>(pf);
        //成功编译, 但是 *pn2是无意义的内存（rubbish）
        int* pn2 = static_cast<int*>(pv);
      // reinterpret_cast<>
        //错误,编译器知道你应该调用static_cast<>
        //int i = reinterpret_cast<int>(f);
        //成功编译, 但是 *pn 实际上是无意义的内存,和 *pn2一样
        int* pi = reinterpret_cast<int*>(pf);
简而言之，static_cast<> 将尝试转换，举例来说，如float-到-integer，而reinterpret_cast<>简单改变编译器的意图重新考虑那个对象作为另一类型。

指针类型（Pointer Types）

指针转换有点复杂，我们将在本文的剩余部分使用下面的类：
class CBaseX
      {
      public:
      int x;
      CBaseX() { x = 10; }
      void foo() { printf("CBaseX::foo() x=%d\n", x); }
      };
      class CBaseY
        {
        public:
        int y;
        int* py;
        CBaseY() { y = 20; py = &y; }
        void bar() { printf("CBaseY::bar() y=%d, *py=%d\n", y, *py); 
        }
        };
      class CDerived : public CBaseX, public CBaseY
        {
        public:
        int z;
        };
情况1：两个无关的类之间的转换 



      // Convert between CBaseX* and CBaseY*
      // CBaseX* 和 CBaseY*之间的转换
      CBaseX* pX = new CBaseX();
      // Error, types pointed to are unrelated
      // 错误， 类型指向是无关的
      // CBaseY* pY1 = static_cast<CBaseY*>(pX);
      // Compile OK, but pY2 is not CBaseX
      // 成功编译, 但是 pY2 不是CBaseX
      CBaseY* pY2 = reinterpret_cast<CBaseY*>(pX);
      // System crash!!
      // 系统崩溃!!
      // pY2->bar();
正如我们在泛型例子中所认识到的，如果你尝试转换一个对象到另一个无关的类static_cast<>将失败，而reinterpret_cast<>就总是成功“欺骗”编译器：那个对象就是那个无关类。

情况2：转换到相关的类
      1. CDerived* pD = new CDerived();
      2. printf("CDerived* pD = %x\n", (int)pD);
      3. 
      4. // static_cast<> CDerived* -> CBaseY* -> CDerived*
      //成功编译，隐式static_cast<>转换
      5. CBaseY* pY1 = pD;
      6. printf("CBaseY* pY1 = %x\n", (int)pY1);
      // 成功编译, 现在 pD1 = pD
      7. CDerived* pD1 = static_cast<CDerived*>(pY1);
      8. printf("CDerived* pD1 = %x\n", (int)pD1);
      9. 
      10. // reinterpret_cast
      // 成功编译, 但是 pY2 不是 CBaseY*
      11. CBaseY* pY2 = reinterpret_cast<CBaseY*>(pD);
      12. printf("CBaseY* pY2 = %x\n", (int)pY2);
      13. 
      14. // 无关的 static_cast<>
      15. CBaseY* pY3 = new CBaseY();
      16. printf("CBaseY* pY3 = %x\n", (int)pY3);
      // 成功编译,尽管 pY3 只是一个 "新 CBaseY()"
      17. CDerived* pD3 = static_cast<CDerived*>(pY3);
      18. printf("CDerived* pD3 = %x\n", (int)pD3);
      ---------------------- 输出 ---------------------------
      CDerived* pD = 392fb8
      CBaseY* pY1 = 392fbc
      CDerived* pD1 = 392fb8
      CBaseY* pY2 = 392fb8
      CBaseY* pY3 = 390ff0
      CDerived* pD3 = 390fec
      
注意：在将CDerived*用隐式 static_cast<>转换到CBaseY*（第5行）时，结果是（指向）CDerived*（的指针向后） 偏移了4（个字节）（译注：4为int类型在内存中所占字节数）。为了知道static_cast<> 实际如何，我们不得不要来看一下CDerived的内存布局。

CDerived的内存布局（Memory Layout）
[img]http://www.vckbase.com/document/journal/vckbase48/images/static_cast_layout.gif[/img] 
```

```
http://www.vckbase.com/document/journal/vckbase48/images/static_cast_layout.gif
```

```
如图所示，CDerived的内存布局包括两个对象，CBaseX 和 CBaseY，编译器也知道这一点。因此，当你将CDerived* 转换到 CBaseY*时，它给指针添加4个字节，同时当你将CBaseY*转换到CDerived*时，它给指针减去4。然而，甚至它即便不是一个CDerived你也可以这样做。
当然，这个问题只在如果你做了多继承时发生。在你将CDerived转换 到 CBaseX时static_cast<> 和 reinterpret_cast<>是没有区别的。

情况3：void*之间的向前和向后转换

因为任何指针可以被转换到void*，而void*可以被向后转换到任何指针（对于static_cast<> 和 reinterpret_cast<>转换都可以这样做），如果没有小心处理的话错误可能发生。



    CDerived* pD = new CDerived();
        printf("CDerived* pD = %x\n", (int)pD);
          CBaseY* pY = pD; // 成功编译, pY = pD + 4
        printf("CBaseY* pY = %x\n", (int)pY);
            void* pV1 = pY; //成功编译, pV1 = pY
        printf("void* pV1 = %x\n", (int)pV1);
               // pD2 = pY, 但是我们预期 pD2 = pY - 4
        CDerived* pD2 = static_cast<CDerived*>(pV1);
        printf("CDerived* pD2 = %x\n", (int)pD2);
        // 系统崩溃
        // pD2->bar();
        ---------------------- 输出 ---------------------------
        CDerived* pD = 392fb8
        CBaseY* pY = 392fbc
        void* pV1 = 392fbc
        CDerived* pD2 = 392fbc
     
[b]一旦我们已经转换指针为void*，我们就不能轻易将其转换回原类。在上面的例子中，从一个void* 返回CDerived*的唯一方法是将其转换为CBaseY*然后再转换为CDerived*。 [/b]但是如果我们不能确定它是CBaseY* 还是 CDerived*，这时我们不得不用dynamic_cast<> 或typeid[2]。

注释：
1. dynamic_cast<>，从另一方面来说，可以防止一个泛型CBaseY* 被转换到CDerived*。
2. dynamic_cast<>需要类成为多态，即包括“虚”函数，并因此而不能成为void*。
参考： 
1. [MSDN] C++ Language Reference -- Casting 
2. Nishant Sivakumar, Casting Basics - Use C++ casts in your VC++.NET programs 
3. Juan Soulie, C++ Language Tutorial: Type Casting
推荐链接：如何在运行时确定对象类型（RTTI）
```