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 ?

  • Yes, it's no problem to write yourself ... - Harry
  • @harry, well, then rather the question of laziness. just there is atof, and for some reason it returns 0 for erroneous input. Are there already analogs? - Mikhail Dyomin
  • one
    Of course have. See man strtod - avp
  • @ Mikhail Dyomin: atof ? The atof has no practical applications. The basic function of the translation of a string in double is the function strtod , which reports errors through errno and a pointer. Have you tried strtod ? And it seems that you are trying to solve a non-existent problem. - AnT

2 answers 2

 #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

  • one
    In 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