C/C++中int/long/float/double数值类型与字符串互相转换[总结]
2016-03-16 16:00
806 查看
http://hi.baidu.com/daven172/blog/item/931e9fa6f346fce29052eeb7.html
一、int/long/float/double转字符串
方法1:itoa, ltoa(a表示array数组的意思)
头文件:stdlib.h
示例:
int a = 3;
long b = 23;
char buf1[30] = "";
itoa(a, buf1, 10);//10表示十进制,buf1保存的内容为"3"
char buf2[30] = "";
ltoa(b, buf2, 10);//10表示十进制,buf2保存的内容为"32"
方法2:sprintf
头文件:stdio.h
示例:
int a = 3;
float b = 4.2f;
char buf[30] = "";
sprintf(buf, "%d,%f", a, b);//buf保存的内容为"3,4.2",可对比printf
方法3:ostringstream
头文件:#include <sstream>
using namespace std;
示例:
int a = 3;
float b = 4.2f;
ostringstream s1;
s1<<a<<","<<b;//可对比cout
string s2 = s1.str();//s2保存的内容为"3,4.2"
还可以通过setprecision来设置输出浮点数的精度
s1 << setiosflags(ios_base::fixed) <<setprecision(1) << 1.00 ; 那么s1中将是 1.0 其中setprecision设置宽度,setiosflags(ios_base::fixed)表示设定的是小数点后的宽度
二、字符串转int/long/float/double
方法1:atoi,atol,atof
头文件:stdlib.h
示例:
int a = atoi("32");
long b = atol("333");
double c = atof("23.4");
方法2:strtol, strtod
头文件:stdlib.h
示例:
long b = strtol("333", NULL, 10);//10表示十进制
double c = strtod("32.3", NULL);
方法3:sscanf
头文件:stdio.h
示例:
int a;
float b;
sscanf("23 23.4", "%d %f", &a, &b);//对比scanf
方法4:istringstream
头文件:#include <sstream>
using namespace std;
示例:
int a;
float b;
istringstream s1("23 23.4");
s1>>a>>b;//对比cin
同样可以用setprecision 和 setiosflags(ios_base::fixed)来设置精度,见上面的ostringstream
一、int/long/float/double转字符串
方法1:itoa, ltoa(a表示array数组的意思)
头文件:stdlib.h
示例:
int a = 3;
long b = 23;
char buf1[30] = "";
itoa(a, buf1, 10);//10表示十进制,buf1保存的内容为"3"
char buf2[30] = "";
ltoa(b, buf2, 10);//10表示十进制,buf2保存的内容为"32"
方法2:sprintf
头文件:stdio.h
示例:
int a = 3;
float b = 4.2f;
char buf[30] = "";
sprintf(buf, "%d,%f", a, b);//buf保存的内容为"3,4.2",可对比printf
方法3:ostringstream
头文件:#include <sstream>
using namespace std;
示例:
int a = 3;
float b = 4.2f;
ostringstream s1;
s1<<a<<","<<b;//可对比cout
string s2 = s1.str();//s2保存的内容为"3,4.2"
还可以通过setprecision来设置输出浮点数的精度
s1 << setiosflags(ios_base::fixed) <<setprecision(1) << 1.00 ; 那么s1中将是 1.0 其中setprecision设置宽度,setiosflags(ios_base::fixed)表示设定的是小数点后的宽度
二、字符串转int/long/float/double
方法1:atoi,atol,atof
头文件:stdlib.h
示例:
int a = atoi("32");
long b = atol("333");
double c = atof("23.4");
方法2:strtol, strtod
头文件:stdlib.h
示例:
long b = strtol("333", NULL, 10);//10表示十进制
double c = strtod("32.3", NULL);
方法3:sscanf
头文件:stdio.h
示例:
int a;
float b;
sscanf("23 23.4", "%d %f", &a, &b);//对比scanf
方法4:istringstream
头文件:#include <sstream>
using namespace std;
示例:
int a;
float b;
istringstream s1("23 23.4");
s1>>a>>b;//对比cin
同样可以用setprecision 和 setiosflags(ios_base::fixed)来设置精度,见上面的ostringstream
相关文章推荐
- C++字面值常量
- strlen()与sizeof
- C语言学习资料
- C++函数模板
- c++ 二叉树的线索化(前中后序遍历)
- C/C++编译链接过程详解
- OpenGL蓝宝书第五章代码勘误以及惯性坐标系去解释模型变换:Pyramid.cpp
- (转)运算优先级、结合性、求值顺序、副作用和顺序点
- C++如何选择类型
- kmp算法及其c++实现
- C++继承20160214
- C++多态20160214
- C++中常用到的容器
- C++文件读写详解
- C#调用c++ dll 方式
- C++中 引用和指针的区别
- C++ 模板
- 选择排序c语言实现
- C++标准库之substr函数用法
- C++标准库之queue(各函数及其使用全)