Portable printing of exponent of a double to C++ iostreams

后端 未结 3 1627
鱼传尺愫
鱼传尺愫 2021-02-05 12:28

I want to print a double value to std::cout portably (GCC, clang, MSVC++) such that the output is the same on all platforms.

I have a problem with the forma

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-05 13:10

    While Dietmar's answer is the clean and probably only really portable answer, I accidentally found a quick-and-dirty answer: MSVC provides the _set_output_format function which you can use to switch to "print exponent as two digits".

    The following RAII class can be instantiated in your main() function to give you the same behaviour of GCC, CLANG and MSVC.

    class ScientificNotationExponentOutputNormalizer
    {
    public:
        unsigned _oldExponentFormat;
    
        ScientificNotationExponentOutputNormalizer() : _oldExponentFormat(0)
        {
    #ifdef _MSC_VER
            // Set scientific format to print two places.
            unsigned _oldExponentFormat = _set_output_format(_TWO_DIGIT_EXPONENT);
    #endif
        }
    
        ~ScientificNotationExponentOutputNormalizer()
        {
    #ifdef _MSC_VER
            // Enable old exponent format.
            _set_output_format(_oldExponentFormat);
    #endif
        }
    };
    

提交回复
热议问题