字符串与数字之间的转换

来源:互联网 发布:高性能mysql pdf 云盘 编辑:程序博客网 时间:2024/05/04 10:04
//将string转换为double#include <iostream>#include <cstring>using namespace std;int main(){//将string转换为double,可以利用cstr  还有atofstring s("1324.56");double d = atof(s.c_str());cout<<d<<endl;}


//数字转字符串:使用sprintf()函数

char str[10];
int a=1234321;
sprintf(str,"%d",a);
--------------------
char str[10];
double a=123.321;
sprintf(str,"%.3lf",a);
--------------------
char str[10];
int a=175;
sprintf(str,"%x",a);//10进制转换成16进制,如果输出大写的字母是sprintf(str,"%X",a)
--------------------
char *itoa(int value, char* string, int radix); 
同样也可以将数字转字符串,不过itoa()这个函数是平台相关的(不是标准里的),故在这里不推荐使用这个函数。


//字符串转数字:使用sscanf()函数

char str[]="1234321";
int a;
sscanf(str,"%d",&a);
.............
char str[]="123.321";
double a;
sscanf(str,"%lf",&a);
.............
char str[]="AF";
int a;
sscanf(str,"%x",&a); //16进制转换成10进制

另外也可以使用atoi(),atol(),atof().


0 0
原创粉丝点击