【Z一贴】C++ String: How to convert a string into a numeric type?

C++ String: How to convert a string into a numeric type?

Q: How to convert a string into a numeric type?

A: There is one thing that you are not allowed to ignore when you convert a string into a numeric type: the conversion might fail because the
string you are converting might not contain a valid representation of a number.

If, for example, you try to convert the string "Hello" to a number, the conversion must fail.

The old C way (deprecated):

Many people use the 'atoi()', 'atof()' and the other functions from this "family". They're easy to use but have a major drawback: they return 0 both on failure and when converting the string "0", thus making a consistent error detection as good as impossible. We give this little sample for the sake of completeness:

Code:
   
   
const char* str_int = "777"; const char* str_float = "333.3"; int i = atoi(str_int); float f = atof(str_float);


A better way:

A bit more complicated, but also more consistent way is to use 'sscanf()' in one of it's flavors:

Code:
   
   
const char* str_int = "777"; const char* str_float = "333.3"; int i; float f; if(EOF == sscanf(str_int, "%d", &i)) { //error } if(EOF == sscanf(str_float, "%f", &f)) { //error }

Since 'sscanf()' takes a 'const char*' parameter, you can directly use a 'CString' with it:

Code:
   
   
CString str_int( "777"); if(EOF == sscanf(str_int, '%d', &i)) { //error }

Be very careful with the format specifier (i.e. "%d" in this example). 'sscanf()' has no way to check whether the format specifier and the type of the passed variable match each other. If they don't you will get unexpected
results. Also note that 'sscanf()' is able to extract more than one numerical value from a string with one call. Have a look in e.g. MSDN for details.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值