Weird output when printing `NaN` with std::cout and a changed locale
Asked Answered
C

1

6

I am currently trying to build a simple console calculator in C++ and was thinking about what to do when the user types 0/0. In my calculator I convert each number from the users input to a double and therefore get the division 0.0/0.0 which should result in NaN.

However when I try to output this to the console I am noticing some weird behaviors with a changed locale. With large results it is easier to read the number when there is a separator between every 3 digits so I originally changed the local to en_US, which would format me a number like 1234.56 as 1,234.56 which is indeed the wanted behavior. But with NaN as output it didn't quite work as I thought it would.

In the following sample code I use std::sqrt(-1) to get NaN as result since my compiler (MSVC) doesn't allow me to divide 0/0.0. At first I don't specify a locale (which should give me the "C" locale if I am not mistaken, at least I got the same output with nothing vs "C"). After that I changed to locale to "" and "en_US" which both gave me different output with some seemingly random seperators in between.

Code:

#include <iostream>
#include <locale>
#include <cmath>

int main()
{
    //std::cout.imbue(std::locale("C"));
    std::cout << std::sqrt(-1) << std::endl;

    std::cout.imbue(std::locale(""));
    std::cout << std::sqrt(-1) << std::endl;

    std::cout.imbue(std::locale("en_US"));
    std::cout << std::sqrt(-1) << std::endl;

    std::cin.get();
    return 0;
}

Output:

-nan(ind)
-na.n(i.nd)
-na,n(i,nd)

For my calculator not to print some weird output I could just check if the value is NaN before outputting it, but I still wonder why NaN gets represented different (with some weird characters in between) depending on my locale.

Coelho answered 8/7, 2023 at 21:30 Comment(7)
This looks like an obvious bug in the C library.Nectar
@AndreasWenzel Yeah sorry about that I forgot to include it since it worked without anyways for me. It was probably included with iostream in my case. Just added it in case someone else wants to try it.Coelho
You should report a bug.Personification
@Personification How and where would I do that?Coelho
Since you're using Visual Studio, there was a button somewhere in the menus. "Help->report bug", or something similar.Personification
@Coelho I didn't find a similar bugreport so I wrote one. You can login and vote for it if you want MS to pay more attention to it.Allemande
@TedLyngmo thank you for writing one. I already wrote one after posting this question but never updated this post. You can look at my answer to see it.Coelho
C
3

I created a bug report and this was indeed a bug in the standard library and will be fixed in a later version of Visual Studio.

The bug was fixed and the fix is expected in VS 2022 17.8 Preview 2

Coelho answered 16/8, 2023 at 13:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.