C++整型\字符串\数组的相互转换

总体思路:

1. 直接使用itoa转换
2. 用sprinf(buf, "%d", 234")
3. 用ostringstream sout; sout<<234; sout.str()就是转换好的.
从效率角度来说, 1>2>3. 安全性角度来说1<2<3.

例1:

int a=234
char ch[5];
ch=itoa(a);
cout<<ch<<endl;
例2:
#include<iostream.h>
char* IntToStr(int n)
{
	char* a=new char[20];
	int count=1;
	int index=0;
	int i,j;
	int temp=n;
	while((temp=temp/10) !=0)
	{
		count++;
	}
	for(i=count;i>=1;i--)
	{
		temp=n;
	    for(j=1;j<i;j++)
		{
			temp=temp/10;			
		}
		a[index]=temp%10+'0';
		index++;
	}
	a[index]='\0';
	return a;
}
void main()
{	int x=234;
    cout<<::IntToStr(x)<<"\n";
 
}
例3:
#include<stdlib.h>
int atoi(const char *nptr)

其中nptr表示将要转换成整数的字符串
 
例4:(VS2010验证)
#include <string>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int i=1;
string str="结果:";
string str2;
char buf[10];
itoa(i, buf, 10);
str2=str+buf;
cout<<str2;
return 0;
}
例5:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

template <class T, class U>
T lexical_cast(U u)
{
    stringstream sstrm;
    sstrm << u;
    T t;
    sstrm >> t;
    return t;
}

int main()
{
    int a[] = {1,2,3,4,5,6,7,8,9,10};
    string s;
    for(int i = 0; i < 10; ++i)
        s += lexical_cast<string>(a[i]);
    cout << s << endl;
}
例6:
#include<iostream>
using namespace std;
int main()
{
 int a[10]={1,2,3,5,7,8,9,5,3,0};
 char str[256];
 for (int i=0;i<10;i++)
 {
  itoa(a[i],&str[i],10);     //itoa函数
 }
 str[i]='\0';
 cout<<str<<endl;
 return 0;
}
例7:
using namespace std;
int main()
{
 int a[10]={1,2,3,5,7,8,9,5,3,0};
 char str[256];
 for (int i=0;i<10;i++)
 {
  sprintf(&str[i],"%d",a[i]);             //sprintf函数
 }
 str[i]='\0';
 cout<<str<<endl;
 return 0;
}
实例讲解一:http://blog.csdn.net/suzilong11/article/details/7318040
实例讲解二:http://blog.sina.com.cn/s/blog_616694280100ffv6.html
实例讲解三:http://blog.csdn.net/touzani/article/details/1623850/
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FeelTouch Labs

一杯咖啡的鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值