How to parse floating point infinity from std::istream

Viewed 50

I have written a superdumb serialization library for a project that I am working on. I just got bitten by floating point infinity, which I illustrate with the sample program below. I expect the program to print inf -> int, but instead it prints inf -> 0. How to fix it using std::ostream and std::istream interface to give correct answer for floating point infinity (and NaNs)?

#include <limits>
#include <sstream>
#include <iostream>

void serialize(std::ostream& dst, float src) {
    dst << src;
}

void deserialize(float& dst, std::istream& src) {
    src >> dst;
}

int main() {
    const float original = std::numeric_limits<float>::infinity();
    std::stringstream buffer;
    serialize(buffer, original);
    float parsed;
    deserialize(parsed, buffer);
    std::cout << original << " -> " << parsed << '\n';
}
0 Answers
Related