C++整型\字串\陣列的相互轉換
阿新 • • 發佈:2019-01-25
總體思路:
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;
}