C++: string to double

51 篇文章 2 订阅

1. atof vs. stod

from https://blog.csdn.net/guotianqing/article/details/110204759

背景

程序需要从文件中读取double精度的数据。

随着程序的更新,文件也会更新。但有时候,更新了文件,却忘记更新程序,这时启动程序时,就会coredump。

gdb coredump也很容易看出问题,但不能一出问题就让程序crash啊。

于是加了try来catch异常,但是无果,还是dump,于是查了一下,发现了atof的问题。

stod vs atof

atof是c代码里的库函数,用于把字符串转换为double精度的数字,原型如下:

#include <stdlib.h>
double atof (const char* str);
返回值:

正常时,该函数返回double精度的浮点数
如果不能进行有效地转换,返回0.0
如果转换的数值超出了double可以表示的范围,该函数会产生未定义的行为
正常的情况都不用说了,这不正常的情况,似乎也太不正常了。

所以使用它时,要注意处理后两种情况,看看到底是正常的0,还是无效的输入。

未定义的行为,相信C++程序员早已不陌生了,直接认怂就好。

注意,strtod跟它差不多,有一点好的,是第三种情况,它会返回正的/负的HUGE_VAL,并设置errno为ERANGE。

stod是标准c++库函数,在c++11中得到了支持,它把参数指定的字符串转换为double精度的浮点数。

单看上面一句话,是不是就得秒杀atof了。

原型如下:

#include <string>

double stod (const string&  str, size_t* idx = 0);
double stod (const wstring& str, size_t* idx = 0);

其中,idx不是空指针时,该函数还将idx的值设置为数字后str中第一个字符的位置。

返回值:

正常返回double精度浮点数
不能执行转换时,抛出异常invalid_argument
超出double所能表示的范围时,抛出异常out_of_range
无效的idx会导致未定义的行为,一般默认就好
这里提一下,该函数底层使用 strtod 执行转换。

所以,它对于不能够进行有效转换的情况,都会抛出异常,我们try一下就catch住了。

它的兄弟有:std::stof(转换为float单精度), std::stold(转换为long double长双精度),stoi,stol,stoll,stoul,stoull, from_chars(c++17,转换字符序列)。

对于空字符串

这里有一个问题需要注意,就是当输入的参数字符串为空时,两个函数返回的结果并不相同。

如果希望的是,当字符串为空时,返回0,那么atof可以完美达到需求。

如果希望字符串空时,抛出异常,则stod就是这样做的,因为空白的字符串不能进行转换。

它们对应于两种不同的需求,如果认为输入的字符串为空时需要介入处理,使用stod仍然是最佳选择,而如果认为返回0就ok了,那么当使用stod时就要进行处理前的判断了。

测试代码如下:

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main()
{
    try
    {
        string num;
        // num = "-23435";
        
        auto a = atof(num.c_str());
        cout << "atof: " << a << endl;
    
        auto d = stod(num);
        cout << "stod: " << d << endl;
    }
    catch(const exception& e)
    {
        cout << "ex: " << e.what() << endl;
    }

    return 0;
}


执行结果如下:

% ./a.out 
atof: 0
ex: stod

小结

如果符合以下情况:

支持c++11编译
能够处理异常
c++新手,不知道用哪个好
那就使用stod系列函数吧,否则就使用atof。
————————————————
版权声明:本文为CSDN博主「guotianqing」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/guotianqing/article/details/110204759

 

C++ Convert String to Double Speed

from: https://tinodidriksen.com/2011/05/cpp-convert-string-to-double-speed/

(There is also a string-to-int performance test.)

A performance benchmark of which method is faster of converting an std::string to a double. The goal is ending up with a double of the value represented in an std::string.

The tested methods are:

Source for the test is at speed-string-to-double.cpp with cycle.h.

The compilers are Microsoft Visual C++ 2010 with _SECURE_SCL disabled, GNU g++ 4.6.0, and LLVM clang++ from Arch.


Tests were run for converting 100000 string containing doubles in the range +/- 99999.99999. The result for the naive loop and atof() are set as the baseline 100% and the other numbers is time spent relative to those. The naive loop (--> a direct numerical  accumulation char by char) wins by a large margin, but Boost.Spirit is the fastest correct implementation.

Windows: MSVC++ 2010

  • Compiler: MSVC++ 2010 _SECURE_SCL=0
  • Arch: Windows 7 64 bit, 1.60GHz Core i7 Q720, 8 GiB RAM
VC++ 2010TicksRelative to naiveRelative to atof()
naive43662201.000.05
atof()8273277418.951.00
strtod()8318919819.051.01
sscanf()16856838738.612.04
spirit qi189329174.340.23
lexical_cast33237440776.124.02
stringstream36194381682.904.37
stringstream reused24084839255.162.91

Linux: GNU g++ 4.6.0

  • Compiler: GNU g++ 4.6.0 -O3
  • Arch: VirtualBox on the Windows machine, VT-x, Arch Linux, kernel 2.6.38-ARCH, 1 GiB RAM
g++ 4.6.0TicksRelative to naiveRelative to atof()
naive46561591.000.15
atof()306054906.571.00
strtod()309639266.651.01
sscanf()5623519712.081.84
spirit qi207310624.450.68
lexical_cast13952140629.964.56
stringstream18472329839.676.04
stringstream reused10090540721.673.30

Linux: LLVM clang++ 2.9

  • Compiler: clang++ 2.9 -O3
  • Arch: VirtualBox on the Windows machine, VT-x, Arch Linux, kernel 2.6.38-ARCH, 1 GiB RAM
clang++ 2.9TicksRelative to naiveRelative to atof()
naive68048811.000.22
atof()308298654.531.00
strtod()308715144.541.00
sscanf()579039938.511.88
spirit qi244110413.590.79
lexical_cast14933983321.954.84
stringstream19123906628.106.20
stringstream reused10046140514.763.26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值