Re: Reading and Writing float value of infinity to file.
"Jim Langston" <tazmaster@rocketmail.com> wrote in message
news:Gc1Si.76$dr4.63@newsfe02.lga...
"James Kanze" <james.kanze@gmail.com> wrote in message
news:1192788360.167539.75570@i13g2000prf.googlegroups.com...
On Oct 19, 8:56 am, "Jim Langston" <tazmas...@rocketmail.com> wrote:
The output of the following program is:
1.#INF
1
But:
1.#INF
1.#INF
was expected and desired. How can I read a value of infinity
from a stream?
[Snip discussion about C++ not supporing infinity]
Well, this is what I came up with. Output is as I want. Do you see
anything I'm doing wrong here? Of course I'll have to come up with a better
name than "MyFloat".
1.#INF
1 2.2 3.3
1.#INF 2.2 3.3
#include <iostream>
#include <fstream>
#include <limits>
#include <string>
class MyFloat
{
public:
MyFloat( float Value = 0.0f ): Value( Value ) {}
operator float() { return Value; }
float Value;
};
std::istream& operator>>( std::istream& is, MyFloat& mf )
{
if ( is >> mf.Value )
{
if ( mf.Value == 1.0f && is.peek() == '#' )
{
std::string Rest;
is >> Rest;
if ( Rest == "#INF" )
mf.Value = std::numeric_limits<float>::infinity();
}
}
return is;
}
int main(void)
{
float Infinity, Foo = 2.2f, Bar = 3.3f;
Infinity = std::numeric_limits<float>::infinity();
std::cout << Infinity << "\n";
std::ofstream outf("test.txt");
if ( outf.is_open() )
outf << Infinity << " " << Foo << " " << Bar << "\n";
outf.close();
float Value = 0.0f, Value2 = 0.0f, Value3 = 0.0f;
std::ifstream inf("test.txt");
if ( inf.is_open() )
inf >> Value >> Foo >> Bar;
inf.close();
std::cout << Value << " " << Foo << " " << Bar << "\n";
MyFloat MyValue = 0.0f, MyValue2 = 0.0f, MyValue3 = 0.0f;
std::ifstream inf2("test.txt");
if ( inf2.is_open() )
inf2 >> MyValue >> MyValue2 >> MyValue3;
inf2.close();
std::cout << MyValue << " " << MyValue2 << " " << MyValue3 << "\n";
return 0;
}