C++整型\字符串\数组的相互转换
来源:互联网 发布:郑州淘宝加盟判刑 编辑:程序博客网 时间:2024/04/28 02:26
总体思路:
1. 直接使用itoa转换2. 用sprinf(buf, "%d", 234")3. 用ostringstream sout; sout<<234; sout.str()就是转换好的.从效率角度来说, 1>2>3. 安全性角度来说1<2<3.
例1:
int a=234char 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/
- C++整型\字符串\数组的相互转换
- 字符串与整型数组的相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- 字符串与整型的相互转换
- Java的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- SQL位运算
- C++精确计算代码执行时间精度微秒级
- javafx2导出文件选择路径
- 补码问题
- hdu 4010(LinkCutTree)
- C++整型\字符串\数组的相互转换
- 树形DP总结(转)
- SPOJ - WMELON(离散化+暴力or离散化+线段树)【待完善】
- UITableView样式的自定义
- 涂鸦 画线
- android noclassdeffounderror:jxl.workbook
- 生活杂记
- 备份恢复基础复习
- presentModalViewController和dismissModalViewControllerAnimated的使用总结