C/C++中字符串与数字相互转换
来源:互联网 发布:sql语句中union 编辑:程序博客网 时间:2024/05/01 19:50
数字转字符串:
用C++的streanstream:
#include <sstream>
#Include <string>
string num2str(double i)
{
stringstream ss;
ss << i;
return ss.str();
}
字符串转数字:
int str2num(string s)
{
int num;
stringstream ss(s);
ss>>num;
return num;
}
上面方法很简便, 缺点是处理大量数据转换速度较慢..
C library中的sprintf, sscanf 相对更快
可以用 sprintf 函数将数字输出到一个字符缓冲区中. 从而进行了转换.
例如:
已知从0点开始的秒数(seconds) ,计算出字符串"H:M:S", 其中H是小时, M=分钟,S=秒
int H, M, S;
string time_str;
H=seconds/3600;
M=(seconds%3600)/60;
S=(seconds%3600)%60;
char ctime[10];
sprintf(ctime, "%d:%d:%d", H, M, S); // 将整数转换成字符串
time_str=ctime; // 结果
与sprintf对应的是 sscanf 函数, 可以将字符串转换成数字.
char str[] = "15.455";
int i;
float fp;
sscanf( str, "%d", &i ); // 将字符串转换成整数 i = 15
sscanf( str, "%f", &fp ); // 将字符串转换成浮点数 fp = 15.455000
//打印
printf( "Integer: = %d ", i+1 );
printf( "Real: = %f ", fp+1 );
return 0;
输出如下:
Integer: = 16
Real: = 16.455000
补充(by xuzhezhaozhao):
C标准库了提供了 atoi, atof, atol, atoll(C++11标准) 函数将字符串转换成int,double, long, long long 型。
char str[] = "15.455";
double db;
int i;
db = atof(str); // db = 15.455
i = atoi(str); // i = 15
若字符串为string类型,则要用c_str()方法获取其字符串指针,如下:
string str = "15.455";
double db;
int i;
db = atof(str.c_str()); // db = 15.455
i = atoi(str.c_str()); // i = 15
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C语言字符串与数字之间的相互转换
- C标准中的字符串-数字相互转换
- c语言中数字与字符之间的相互转换
- C++中字符串与数字相互转换
- objective-c 中字符串与日期相互转换
- C/C++中ASCII与Unicode字符串相互转换
- objective-c 中字符串与日期相互转换
- C/C++中字符串与数值相互转换
- C语言中字符串与整数的相互转换
- 初步学习Protected Mode(5)
- 消息中间件技术与设备状态在线监测
- Property's synthesized getter follows Cocoa naming convention for returning.
- 图像分割工作总结(五)opencv遍历图像
- 防止表单重复提交的几种策略
- C/C++中字符串与数字相互转换
- paip.myeclipse7 java webservice 最佳实践o228
- Android UIAutomator Test
- it技术网站收藏
- 程序员永远的痛之字符编码的奥秘
- namespace C++
- Session清理解决问题
- IOS的变量前加extern和static字段
- android获得asset资源