使用非标准区域设置编写文件

如果你需要使用不同的区域设置将文件写入默认值,则可以使用 std::localestd::basic_ios::imbue() 为特定文件流执行此操作:

使用指南:

  • 在打开文件之前,应始终将本地应用于流。
  • 一旦流被灌输,你就不应该更改区域设置。

限制的原因: 如果当前区域设置不是独立状态或未指向文件的开头,则使用区域设置阻塞文件流具有未定义的行为。

UTF-8 流(和其他)不是状态独立的。此外,具有 UTF-8 语言环境的文件流可以在文件打开时尝试从文件中读取 BOM 标记; 所以只是打开文件可能会读取文件中的字符,而不会在开头。

#include <iostream>
#include <fstream>
#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 << 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 << 78123.456 << std::endl;

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

如果你的程序使用不同的默认语言环境并且你希望确保读取和写入文件的固定标准,则显式切换到经典 C 语言环境非常有用。这个例子写了一个 C 首选语言环境

78,123.456
78,123.456
78123.456

例如,如果首选语言环境是德语,因此使用不同的数字格式,则示例写入

78 123,456
78,123.456
78123.456

(注意第一行中的小数逗号)。