5

I am trying to read a hex float value through std::cin. However, it just reads in 0. Here is my code so far:

#include <iomanip>
#include <iostream>

int main() {
  double f = 0.0;
  std::cout << ">";
  std::cin >> std::hexfloat >> f;
  std::cout << "Entered: " << f << std::endl;
  return 0;
}

This will result in:

>0x1.921fb5p+1
Entered:0.0

Or if I exclude the 0x:

>1.921fb5p+1
Entered:1.921

I am using g++ 7.0.1 and adding the compiler flag -std=c++11 on Ubuntu 17.

  • 2
    Good chances are that you have discovered an error in your library. According to an [example in C++ reference](http://en.cppreference.com/w/cpp/io/manip/fixed) your code is supposed to work. – Sergey Kalinichenko Oct 19 '17 at 18:03
  • Which compiler / library / OS are you running? (Also compilation flags) – Borgleader Oct 19 '17 at 18:10
  • gcc-5.4.1 gets the example on [cppreference](http://en.cppreference.com/w/cpp/io/manip/fixed) wrong; `Parsing 0x1P-1022 as hex gives 0` – Steve Lorimer Oct 19 '17 at 18:12
  • 2
    https://stackoverflow.com/questions/42604596/read-and-write-using-stdhexfloat – Fausto Carvalho Marques Silva Oct 19 '17 at 18:14
  • 1
    Using wandox: [g++](https://wandbox.org/permlink/rVoZrRxOeMd1mgDs) gives incorrect value, while [clang++](https://wandbox.org/permlink/wcSVe6xIvu0WIRQo) gives correct ones – Amadeus Oct 19 '17 at 18:16
  • VS C++ had a bug similar to this: http://www.beta.microsoft.com/VisualStudio/feedbackdetail/view/742775/std-hexfloat-not-working-with-istream-operator – Fausto Carvalho Marques Silva Oct 19 '17 at 18:22
  • @Borgleader I am using `g++ -std=c++11 main.cpp` on ubuntu 17 – Arden Rasmussen Oct 19 '17 at 22:24
  • Apparently, this is expected behavior according to the C++ standard. See this comment: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81122#c1 . – Ruslan Mar 13 '18 at 16:12
  • The same question was asked in the linked question and a workaround was given in the answer. Since that question has an answer, I marked this one as a duplicate. – David Hammen Dec 05 '18 at 21:55
  • @Ruslan - This apparently is a bug in the language specification. The gcc developers are being overly pedantic here, IMHO. In other places where compiler / library developers see a bug in the c++ spec, they (a) issue a bug report to the c++ committee, and (b) make their implementation do the "right thing". ... – David Hammen Dec 05 '18 at 22:00
  • The "right thing" here is rather obvious: `cin >> std::hexfloat >> f` explicitly tells the implementation that the next item to be parsed is a floating point number in hexfloat format. The C language has been doing the "right thing" in this regard for almost twenty years. Clang++ does the right thing, too. It's not hard. – David Hammen Dec 05 '18 at 22:04

0 Answers0