---
title: "C++ 入门：数据类型转换"
author: "ileson"
date: "2011-09-07T10:19:07Z"
tags: ["C++"]
categories: ["编程语言"]
slug: "c"
draft: false
lastmod: "2013-05-08T11:11:11Z"
id: 1167279
url: "https://ileson.iteye.com/blog/1167279"
---

```C++
CString str;
	//1、基本类型转成 字符串
	int i=1;
	long l=2;
	float f=30.0;
	double d=4056.99001;
    char c[100];
	itoa(i,c,10);//转换成十进制的字符串
	itoa(l,c,2);//转换成二进制的字符串
	sprintf(c,"%0.2f",f);
	sprintf(c,"%0.2lf",d);

	str.Format("%s",c);
	
	//2、字符串转换成其它数据类型
	strcpy(c,"123456");
	i=atoi(c);
	l=atol(c);
	//f=atof(c);
	//d=atof(c);//字符串如何转成double?????

	str.Format("int=%d\n long=%d\n float=%0.2f\n double=%0.2ld\n",i,l,f,d);
	AfxMessageBox(str);
```

助记：itoa  各 atoi  这两个莫名其妙的方法，不好记，其实是个短句；
      itoa: int  to  a  整型到字符
      atoi: a    to  int 字符到整型
      

```C

/**
 *整型转成字符型。
 */
char * int2char(int inta){
    char *str;
    sprintf(str,"%d",inta);
    return str;
}

```





> [url=http://blog.csdn.net/wxb_nudt/article/details/2938242]http://blog.csdn.net/wxb_nudt/article/details/2938242[/url]