Note that there are some explanatory texts on larger screens.

plurals
  1. PONaN ASCII I/O with Visual C++
    primarykey
    data
    text
    <p>I want to read and write NaN values from/into text files using iostream and Visual C++. When writing a NaN value, i get <code>1.#QNAN</code>. But, reading it back outputs <code>1.0</code> .</p> <pre><code>float nan = std::numeric_limits&lt;float&gt;::quiet_NaN (); std::ofstream os("output.txt"); os &lt;&lt; nan ; os.close(); </code></pre> <p>The output is <code>1.#QNAN</code> .</p> <pre><code>std::ifstream is("output.txt"); is &gt;&gt; nan ; is.close(); </code></pre> <p><code>nan</code> equals <code>1.0</code>.</p> <p><strong>Solution</strong></p> <p>Finally, as suggested by awoodland, I've come up with this solution. I chose "nan" as a string representation of a NaN. Both &lt;&lt; and >> operators are overridden.</p> <pre><code>using namespace ::std; class NaNStream { public: NaNStream(ostream&amp; _out, istream&amp; _in):out(_out), in(_in){} template&lt;typename T&gt; const NaNStream&amp; operator&lt;&lt;(const T&amp; v) const {out &lt;&lt; v;return *this;} template&lt;typename T&gt; const NaNStream&amp; operator&gt;&gt;(T&amp; v) const {in &gt;&gt; v;return *this;} protected: ostream&amp; out; istream&amp; in; }; // override &lt;&lt; operator for float type template &lt;&gt; const NaNStream&amp; NaNStream::operator&lt;&lt;(const float&amp; v) const { // test whether v is NaN if( v == v ) out &lt;&lt; v; else out &lt;&lt; "nan"; return *this; } // override &gt;&gt; operator for float type template &lt;&gt; const NaNStream&amp; NaNStream::operator&gt;&gt;(float&amp; v) const { if (in &gt;&gt; v) return *this; in.clear(); std::string str; if (!(in &gt;&gt; str)) return *this; if (str == "nan") v = std::numeric_limits&lt;float&gt;::quiet_NaN(); else in.setstate(std::ios::badbit); // Whoops, we've still "stolen" the string return *this; } </code></pre> <p>A minimal working example: a finite float and a NaN are written into a stringstream and then read back.</p> <pre><code>int main(int,char**) { std::stringstream ss; NaNStream nis(ss, ss); nis &lt;&lt; 1.5f &lt;&lt; std::numeric_limits&lt;float&gt;::quiet_NaN (); std::cout &lt;&lt; ss.str() &lt;&lt; std::endl; // OUTPUT : "1.5nan" float a, b; nis &gt;&gt; a; nis &gt;&gt; b; std::cout &lt;&lt; a &lt;&lt; b &lt;&lt; std::endl; // OUTPUT : "1.51.#QNAN" } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload