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.
iostream
in my case. Just added it in case someone else wants to try it. – Coelho