How to detect if atof or _wtof fails?

How to determine if atof or _wtof cannot convert a string to double? But not trying to check if the result is different from 0.0, because my input may be 0.0. Thanks!

+7
source share
2 answers

Do not use atof . Instead, use strtod , from <cstdlib> , and also note errno from <cerrno> :

 // assume: "char * mystr" is a null-terminated string char * e; errno = 0; double x = std::strtod(mystring, &e); if (*e != '\0' || // error, we didn't consume the entire string errno != 0 ) // error, overflow or underflow { // fail } 

Pointer e indicates one after the last character consumed. You can also check e == mystr to see if any characters were used.

There is also std::wcstod for working with wchar_t strings, from <cwstring> .

In C ++ 11, you also have std::to_string / std::to_wstring , from <string> , but I believe that this throws an exception if the conversion fails, which may not be the desired failure mode when working with external data .

+11
source

Using atof , you cannot. But since this is C ++, I suggest you use std::stringstream and check it with operator ! after applying operator >> to double .

+1
source

All Articles