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

VC++中数值与字符串相互转化(总结)

2014-04-08 17:30 281 查看
环境:win7系统 64位 VS2008平台

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
using namespace std;
int main()
{
/*******************数值到字符串**************/
int a_int=22;
long l_long=2147483647;
float f_float=12.5;
double d_double=1.5;
char ary[100]="";

//_itoa_s/_ltoa_s; #include <stdlib.h>
_itoa_s(a_int,ary,2);//二进制-10110
_itoa_s(a_int,ary,8);//八进制-26
_itoa_s(a_int,ary,10);//十进制-22
_itoa_s(a_int,ary,16);//十六进制-16
_ltoa_s(l_long,ary,10);//十进制-33

//sprintf_s 头文件:stdio.h
sprintf_s(ary,"%.2f",f_float);//保留两位小数 1.50
cout<<ary<<endl;
sprintf_s(ary,"%f",d_double);//默认格式 1.500000
cout<<ary<<endl;

//ostringstream 头文件:sstream
ostringstream sstr;
sstr<<f_float;
string str=sstr.str();
/*******************数值到字符串**************/

/*******************字符串到数值**************/
//atoi/atol/atof 头文件:stdlib.h
int b_int=atoi("32");
long b_long= atol("333");
float b_double = atof("23.4");//double 也能凑合着用

//sscanf_s 头文件:stdio.h
sscanf_s ("23 23.4", "%d %f", &b_int, &b_double);

//istringstream 头文件:sstream
istringstream s1("23 23.4");
s1>>b_int>>b_double;
/*******************字符串到数值**************/

}


注意:

vs2008推荐使用_itoa_s、_ltoa_s这两种方法,否则会有警告。
个人经验,慎用ostringstream、istringstream,在使用过程中出现了无法理解的错误。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: