Is there such thing as invalid floating point ?

M

mathieu

Hi,

I am working on an IO library, and I am reading a binary blob which
represent a floating point. I would like to know what is the correct
way to interpret it. For integer type using a stringstream works like
a charm, but for floating point I am getting a behavior that I don't
quite understand, for instance (*).
BTW NaN is the IEEE with all bit set, right ? What is the
representation for infinity ?

Thanks !
-Mathieu

(*)
#include <limits>
#include <iostream>
#include <sstream>

int main()
{
double inf = std::numeric_limits<double>::infinity();
//double nan = std::numeric_limits<double>::quiet_NaN();
std::cout << inf << std::endl;
std::cout << nan << std::endl;
std::stringstream ss;
ss << inf;
double out;
ss >> out;
std::cout << out << std::endl;
return 0;
}

returns:
inf
nan
4.86135e-270
 
M

mathieu

Hi,

I am working on an IO library, and I am reading a binary blob which
represent a floating point. I would like to know what is the correct
way to interpret it. For integer type using a stringstream works like
a charm, but for floating point I am getting a behavior that I don't
quite understand, for instance (*).
BTW NaN is the IEEE with all bit set, right ? What is the
representation for infinity ?

Thanks !
-Mathieu

(*)
#include <limits>
#include <iostream>
#include <sstream>

int main()
{
double inf = std::numeric_limits<double>::infinity();
//double nan = std::numeric_limits<double>::quiet_NaN();
std::cout << inf << std::endl;
std::cout << nan << std::endl;
std::stringstream ss;
ss << inf;
double out;
ss >> out;
std::cout << out << std::endl;
return 0;

}

returns:
inf
nan
4.86135e-270


D'oh ! I am missing the if test:

if( ss >> out )
std::cout << out << std::endl;

My issue is solved, I know how to detect invalid floating point value.

Sorry for the noise,

-Mathieu
 
R

Ron Natalie

mathieu said:
double out;
ss >> out;

You need to check the error state here. The compiler will
not read 'inf' into double. It fails and leaves the out variable
with what ever non-initialized value it had before.

double out = 123.456;

if(ss >> out) {
cout << "input failed (just for giggles out = " << out << "\n";
} else {
cout << out;
}
 
R

Ron Natalie

mathieu said:
D'oh ! I am missing the if test:

if( ss >> out )
std::cout << out << std::endl;

My issue is solved, I know how to detect invalid floating point value.

Don't forget to clear the error if you want to read anything further
from that stream.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top