Writing files with non-standard locale settings

suggest change

If you need to write a file using different locale settings to the default, you can use std::locale and std::basic_ios::imbue() to do that for a specific file stream:

Guidance for use:

Reasons for Restrictions: Imbuing a file buffer is undefined behavior if the file is not at its beginning, the current encoding is state-dependent (codecvt::encoding() returns -1), and the new locale uses a different codecvt facet.

UTF-8 is usually a variable-width encoding, not a state-dependent one. A file stream with a UTF-8 locale may still read a BOM when the file is opened, so opening the file can advance the position past the beginning.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <locale>

int main()
{
  std::cout << "User-preferred locale setting is "
            << std::locale("").name().c_str() << std::endl;

  // Write a floating-point value using the user's preferred locale.
  std::ofstream ofs1;
  ofs1.imbue(std::locale(""));
  ofs1.open("file1.txt");
  ofs1 << std::fixed << std::setprecision(3) << 78123.456 << std::endl;

  // Use a specific locale (names are system-dependent)
  std::ofstream ofs2;
  ofs2.imbue(std::locale("en_US.UTF-8"));
  ofs2.open("file2.txt");
  ofs2 << std::fixed << std::setprecision(3) << 78123.456 << std::endl;

  // Switch to the classic "C" locale
  std::ofstream ofs3;
  ofs3.imbue(std::locale::classic());
  ofs3.open("file3.txt");
  ofs3 << std::fixed << std::setprecision(3) << 78123.456 << std::endl;
}

Explicitly switching to the classic ā€œCā€ locale is useful if your program uses a different default locale and you want to ensure a fixed standard for reading and writing files. With a ā€œCā€ preferred locale, the example writes

78123.456
78,123.456
78123.456

If, for example, the preferred locale is German and hence uses a different number format, the example writes

78.123,456
78,123.456
78123.456

(note the decimal comma in the first line).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents