Tricky Situation: Atof function converting strings to inf or nan

This blog post says about a tricky situation when using atof function. The atof function converts a string argument to a floating point number.

If the string to be converted starts with "inf" or "nan", the atof function converts the string to inf/nan instead of converting to 0.
inf represents "Positive Infinity" and nan represents a value which is "Not a Number".

For eg: The following strings will convert to inf when using atof function.
  • Information -> inf
  • Infection -> inf
  • Influenza -> inf
  • etc...
The following strings will convert to nan when using atof function.
  • Nanotechnology -> nan
  • Nanogram -> nan
  • etc...
This issue can cause downstream impacts if you are using the converted values to be saved to database or other application.

The following C++ program shows the above issue:


















This issue can be corrected by using a simple which checks if the string starts with inf and if so, it can be programmed to prevent from passing to atof function and parse 0 instead.

The function looks like the below:


if (((word[0] == 'i') || (word[0] == 'I')) && ((word[1] == 'n') || (word[1] == 'N')) && ((word[2] == 'f') || (word[2] == 'F')))
 {
  value1 = 0;
 }
 else
 {
  value1 = atof(word);
 }

On debugging, we can see that correct value of 0 is passed (as shown below)


Similar Posts:

1) Anonymous classes in C++
2) Program to check whether a system is big-endian or little-endian

Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Java program to check if an array is bitonic

Using foreach method with list in Java 8