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

来源:互联网 发布:成都理工大学网络教育 编辑:程序博客网 时间:2024/05/29 12:38

环境: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.hsprintf_s(ary,"%.2f",f_float);//保留两位小数 1.50 cout<<ary<<endl;sprintf_s(ary,"%f",d_double);//默认格式 1.500000cout<<ary<<endl;//ostringstream 头文件:sstreamostringstream sstr;sstr<<f_float;string str=sstr.str();/*******************数值到字符串**************//*******************字符串到数值**************///atoi/atol/atof 头文件:stdlib.hint 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 头文件:sstreamistringstream s1("23 23.4");s1>>b_int>>b_double;/*******************字符串到数值**************/}

注意:

  • vs2008推荐使用_itoa_s、_ltoa_s这两种方法,否则会有警告。
  • 个人经验,慎用ostringstream、istringstream,在使用过程中出现了无法理解的错误。


0 0