I am facing problem in reading some floating point numbers from a text file. Some of the numbers are "inf" which are read as 0 by the standard >> operator. So I wrote an overload. But the compiler is not happy :) Refer to the following code.
#include <cmath>
#include <string>
#include <cstrlib>
#include <iostream>
usingnamespace std;
istream &operator>> (istream &stream, double &o)
{
string s;
stream >> s;
if (s == "inf") o = HUGE_VAL;
elseif (s == "-inf") o = -HUGE_VAL;
else o = atof (s.c_str ());
return stream;
}
int main (void)
{
double f;
cin >> f;
// Compiler is confused.
// Whether to call the standard >> operator
// Or to call the one defined above.
return 0;
}
The compilation output is as follows:
main.cxx: In function ‘int main()’:
main.cxx:24: error: ambiguous overload for ‘operator>>’ in ‘(std::istream&)(& std::cin) >> f’
/usr/lib/gcc/i686-redhat-linux/4.4.2/../../../../include/c++/4.4.2/istream:206:note: candidates
are: std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>
(double&) [with _CharT = char, _Traits = std::char_traits<char>]
main.cxx:9: note: std::istream& operator>>(std::istream&, double&)
Any suggestion?
It is interesting to note that HUGE_VAL produces "inf" while printed with cout. Then why would cin read "inf" as 0?
Further the C-function atof treats "inf" as HUGE_VAL.
Since cin is an instantiation of istream, you need to overload it within istream. Overloading it globally, in no way, ties it to cin. Instead, you've overloaded the global operator >> (I believe this is the right-bit-shift operator). Note that it's a bad idea to modify the <iostream> header module.
main.cxx:24: error: ambiguous overload for ‘operator>>’ in ...
There is the istream::operator >> (double &val) already in istream and compiler can't solve the overloading of this function, because they are absolutely equal. http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/
And why don't you want to read the data using atof?
I really don't know, but I think they are declared in the global scope to avoid possible conflicts connected with the 'char' type, which can be either signed or unsigned depending on a compiler.
if they are the members of the class, after the instantiation of the template (with CharT == signed char == char, for example), there will be two istream::operator >> (signed char &val), that is illegal.