Skip to content

Instantly share code, notes, and snippets.

@vlantonov
Created March 22, 2022 07:26
Show Gist options
  • Select an option

  • Save vlantonov/367e3f30b9cb92abebc8d1bad452411a to your computer and use it in GitHub Desktop.

Select an option

Save vlantonov/367e3f30b9cb92abebc8d1bad452411a to your computer and use it in GitHub Desktop.
Locales in C++
#include <cmath>
#include <iostream>
#include <locale>
#include <sstream>
bool checkFloatParse()
{
constexpr double number = 1.5;
constexpr auto numberString = "1.5";
std::istringstream os(numberString);
double value = NAN;
os >> value;
if (number != value) {
std::cout << "Value " << number << " != " << value << " to parsed for global locale: " << os.getloc().name() << '\n';
return false;
}
return true;
}
int main()
{
std::locale::global(std::locale("bg_BG.UTF-8"));
// std::setlocale(LC_NUMERIC, "bg_BG.UTF-8"); // affects std::stof
const auto num = "1.2";
std::istringstream os(num);
os.imbue(std::locale("bg_BG.UTF-8"));
double value = NAN;
if (!(os >> value)) {
std::cout << "Fail!\n";
}
std::cout << value << '\n';
std::cout << "Current locale: " << std::setlocale(LC_ALL, nullptr) << '\n';
std::cout << checkFloatParse() << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment