字符串:怎样转换字符串为数字类型?
当将字符串转换为数值类型时, 有一项东西你不允许忽略: 转换可能因为你正在转换的字符串可能不包含有效的数字表示法而失败
例如, 如果你想将"Hello"转换为数字, 转换将失败
老的C方法(不赞成)
许多人用atoi(), atof() 和这个“家族”中的其它函数. 它们方便应用,但是有一个重要的缺点: 在转换失败和转换字符串"0"时都返回0, 这样使得一致性错误检查变得几乎不可能。 为了完整性我们给出了小段代码:
代码: -------------------------------------------------------------------------------- const char* str_int = "777"; const char* str_float = "333.3"; int i = atoi(str_int); float f = atof(str_float); --------------------------------------------------------------------------------
一个更好的办法:
更有一点复杂, 更遗一致的办法是利用sscanf()
代码: -------------------------------------------------------------------------------- const char* str_int = "777"; const char* str_float = "333.3"; int i; float f; if(EOF == sscanf(str_int, "%d", &i)){ //错误 } if(EOF == sscanf(str_float, "%f", &f)){ //错误 } --------------------------------------------------------------------------------
Since sscanf() takes a const char* parameter, you can directly use a CString with it: 因为sscanf()用const char* 作为参数, 所以你可以直接用CString作参数:
代码: -------------------------------------------------------------------------------- CString str_int("777"); if(EOF == sscanf(str_int, "%d", &i)){ //error } --------------------------------------------------------------------------------
小心格式描述符(如本例中的"%d")。 sscanf()没有办法检查格式描述符与传递变量的类型匹配与否。如果不匹配你将得到不可预期的结果。 同样注意sscanf()可以一次从字符串中提取一个或多个数值。 详细信息请查阅MSDN。
C++ 方法
如下的例子展示了利用标准C++类的来完成这个任务的模板函数
代码: -------------------------------------------------------------------------------- #include <string> #include <sstream> #include <iostream>
template <class T> bool from_string(T &t, const std::string &s, std::ios_base & (*f)(std::ios_base&)) { std::istringstream iss(s); return !(iss>>f>>t).fail(); }
int main() { int i; float f; // from_string()的第三个参数应为如下中的一个 // one of std::hex, std::dec 或 std::oct if(from_string<int>(i, std::string("ff"), std::hex)){ std::cout<<i<<std::endl; } else{ std::cout<<"from_string failed"<<std::endl; } if(from_string<float>(f, std::string("123.456"), std::dec)) { std::cout<<f<<std::endl; } else{ std::cout<<"from_string failed"<<std::endl; } return 0; }
/* 输出: 255 123.456 */ --------------------------------------------------------------------------------
这个方法不仅仅非常别致, 而且也是类型安全的, 因为编译器在编译时会根据操作数的类型将挑选适当的std::istringstream ::operator >>()。 
|