What is atoi equivalent for 64bit integer(uint64_t) in C that works on both Unix and Windows?

前端 未结 7 1509
失恋的感觉
失恋的感觉 2021-02-02 08:02

I\'m trying to convert 64bit integer string to integer, but I don\'t know which one to use.

相关标签:
7条回答
  • 2021-02-02 08:43

    When choosing between C-style functions like strtoll (which are of course easy to use with std::string as well) and std::stoll (which at first glance appears better suited for std::string) or boost::lexical_cast: Be aware that the two latter will throw exceptions in case they cannot parse the input string or the range overflows. Sometimes this is useful, sometimes not, depends what you're trying to achive.

    If you are not in control of the string to parse (as it's external data) but you want to write robust code (which always should be your desire) you always need to expect corrupted data injected by some malicious attacker or broken outside components. For corrupted data strtoll will not throw but needs more explicit code to detect illegal input data. std::stoll and boost::lexical_cast do auto detect and signal crappy input but you must make sure to catch exceptions somewhere to avoid being terminated(TM).

    So choose one or the other depending on the structure of the surrounding code, the needs of the parsed results (sometimes illegal data being "parsed" into a 0 is absolutely OK) the source of the data to parse and last but not least your personal preferences. Neither of the functions available is generally superiour to the others.

    0 讨论(0)
提交回复
热议问题