字符串与浮点数相互转换
2010-08-10 15:48:11
ftoa 浮点数转化为字符串 atof 数字字符串字符串转化为双精度浮点数 在C++编程中,整数转化为字符串、字符串转化为整数或浮点数很常用,尤其是在linux下编程。 其中,VC下提供了itoa和atoi函数可以实现整数转化为字符串和字符串转化为整数。调用方法是: #include<stdlib> int main() { int n = 123; char ch = itoa(n); n = atoi(ch); return 0; } 不过VC并未提供字符串转化为浮点数的函数 而linux下连整数与字符串之间转化的函数都没提供。所以这里顺手写了三个函数可供参考 整数转化为字符串: #include<string> #include<sstream> string int2str(int &i) { string s; stringstream ss(s); ss << i; return ss.str(); } 调用了sstream和string两个库。 字符串转化为整数: int char2int(char ch[]) { int num = 0; for(int i = 0; ch[i]; i++) { num = num*10 + ch[i] - '0'; } return num; } 字符串转化为浮点数: double char2double(char ch[]) { double intg = 0, fl = 0; int flag = 0; for(int i = 0; ch[i]; i++) { if(!flag) { if(ch[i] == '.')flag = 1; else { intg = intg*10 + ch[i] - '0'; } } else { fl = fl*10 + ch[i] - '0'; flag++; } } for(int i = flag; i > 1; i--) { fl /= 10; } return intg + fl; } 由于要分别考虑整数和小数部分,这个程序有点长且不是那么美观 |
|