#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

// Read one whole line so a failed conversion cannot trap the input stream.
bool readNumber(const std::string& prompt, double& value, double low, double high) {
    std::string line;
    while (std::cout << prompt && std::getline(std::cin, line)) {
        std::istringstream input(line);
        char extra = '\0';
        if (input >> value && !(input >> extra) && std::isfinite(value)
            && value >= low && value <= high) {
            return true;
        }
        std::cout << "Enter a finite number in [" << low << ", " << high << "].\n";
    }
    std::cerr << "Input ended before a valid number was supplied.\n";
    return false;
}

struct Temperatures {
    double celsius;
    double kelvin;
};

Temperatures convertFromFahrenheit(double fahrenheit) {
    const double celsius = (fahrenheit - 32.0) * (5.0 / 9.0);
    // Round-off at the absolute-zero boundary must not print negative Kelvin.
    return {celsius, std::max(0.0, celsius + 273.15)};
}

int main() {
    double fahrenheit = 0.0;
    if (!readNumber("Temperature in F: ", fahrenheit, -459.67, 1e6)) return 1;
    const Temperatures result = convertFromFahrenheit(fahrenheit);
    std::cout << std::fixed << std::setprecision(3)
              << "Celsius: " << result.celsius << '\n'
              << "Kelvin: " << result.kelvin << '\n';
}
