C++整型\字符串\数组的相互转换
2013-07-29 19:53
381 查看
总体思路:
例1:
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/
相关文章推荐
- 字符串与整型数组的相互转换
- C++ 整型和字符串相互转换
- C++ 整型和字符串相互转换
- 程序目的:实现c++整型和字符数组,字符串的相互转化
- C++ 整型和字符串相互转换(转载)
- 『C/C++』整型和字符串相互转换
- C++ 整型和字符串相互转换(转载)
- js数组与字符串的相互转换方法
- 字符串和字符数组相互转换
- C++不同类型字符串之间的相互转换
- java中字符数组和字符串的相互转换
- C++的string到C的字符串数组的转换
- JS怎么把字符串数组转换成整型数组
- MFC中CString与字符数组与整型的相互转换
- js数组与字符串的相互转换方法
- js数组与字符串的相互转换方法 数组常用的方法
- Java中把字符串数组转换成整型数组 (未测试)
- C# 字符串与字节数组相互转换
- C++抽象编程——字符串与整数之间的相互转换详解
- C++整型和字符串转换