Is there a ready-made function in c ++ that could try to convert a string to a number ( double for example), and in case of failure would return not zero, but for example NAN ?
2 answers
#include <iostream> #include <cmath> double my_atof(const char *str) { double d; try { d = std::stod(str); } catch (...) { return std::nan(""); } return d; } int main() { double d = my_atof("0"); std::cout << d << std::endl; d = my_atof("0.0f"); std::cout << d << std::endl; d = my_atof("3.445"); std::cout << d << std::endl; d = my_atof("www"); std::cout << d << std::endl; d = my_atof(" "); std::cout << d << std::endl; } 0
0
3.445
nan
nan
- oneIn your variant, the string "0" will be incorrectly processed and everything that one way or the other means 0, the main reason for the question is that you need to correctly process the zero too, but do not bother with a separate line checking whether it is 0 or No - Mikhail Dyomin
- Changed the answer. ..... - JaponDemon
|
public: static double ToDouble( String^ value ) Example:
double targetNumber = Convert::ToDouble(value2); "Failure" - try{} catch(...){} to help
- no .. it's not with ++ - JaponDemon
- link are you sure? - Vitaliy Shebanits
- Not against your answer, but it is not with ++. By reference - .NET Framework - JaponDemon pm
- Explain in more detail what your solution is, and how it will help
try{} catch(...){}- Cerbo
|
atof? Theatofhas no practical applications. The basic function of the translation of a string indoubleis the functionstrtod, which reports errors througherrnoand a pointer. Have you triedstrtod? And it seems that you are trying to solve a non-existent problem. - AnT