您的位置:首页 > 编程语言 > C语言/C++

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

2013-07-29 19:53 381 查看
总体思路:

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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: