using namespace std;
int main(int argc, char *argv[]) {
char c[] = {'0','.','5'};
//char c[] = "0.5";
float f = atof(c);
cout << f*10;
if(c[3] != '\0')
{
cout << "YES";
}
}
OUTPUT: 5YES
Does atof work with non-null terminated character arrays too? If so, how does it know where to stop?
No, it doesn't.
std::atof
requires a null-terminated string in input. Failing to satisfy this precondition is Undefined Behavior.Undefined Behavior means that anything could happen, including the program seeming to work fine. What is happening here is that by chance you have a byte in memory right after the last element of your array which cannot be interpreted as part of the representation of a floating-point number, which is why your implementation of
std::atof
stops. But that's something that cannot be relied upon.You should fix your program this way:
It must either be 0 terminated or the text must contain characters that do not belong to the number.
No... atof() requires a null terminated string.
If you have a string you need to convert that is not null terminated, you could try copying it into a target buffer based on the value of each char being a valid digit. Something to the effect of...
std::string already terminate a string with NULL!
So why not
You can also do it with the stringstream or boost::lexical_cast
http://www.boost.org/doc/libs/1_53_0/doc/html/boost_lexical_cast.html http://www.cplusplus.com/reference/sstream/stringstream/
From the description of the
atof()
function on MSDN (probably applies to other compilers) :No,
atof
does not work with non-null terminated arrays: it stops whenever it discovers zero after the end of the array that you pass in. Passing an array without termination is undefined behavior, because it leads the function to read past the end of the array. In your example, the function has likely accessed bytes that you have allocated tof
(although there is no certainty there, becausef
does not need to followc[]
in memory).The above prints
5.678
, pointing out the fact that a read past the end of the array has been made.