繁体   English   中英

std::fstream 在 msvc 和 g++ 上使用 utf-8 的不同行为

[英]std::fstream different behavior on msvc and g++ with utf-8

std::string path("path.txt");
std::fstream f(path);
f.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t>));
std::string lcpath;
f >> lcpath;

path.txt上的path.txt读取 utf-8 文本失败,在 Windows 上使用 MSVC 编译器,因为lcpath无法将路径理解为 utf-8。

使用 g++ 编译时,以下代码在 linux 上正常工作。

    std::string path("path.txt");
    std::fstream ff;
    ff.open(path.c_str());
    std::string lcpath;
    ff>>lcpath;

默认情况下,windows(MSVC) 上的fstream是否仅假设 ascii?

在第一个片段中,如果我使用wstring更改string并使用wfstream更改fstream ,则wfstream lcpath在 Windows 上获得正确的值。

编辑:如果我使用MultiByteToWideChar()转换读取的lcpath ,我会得到正确的表示。 但是为什么我不能在 Windows 上直接将 UTF-8 字符串读入std::string中?

注入打开的文件可能是有问题的:

http://www.cplusplus.com/reference/fstream/filebuf/imbue/

如果 loc 与文件流缓冲区当前使用的区域设置不同,则内部位置指针指向文件的开头,或者其编码与状态无关。 否则,它会导致未定义的行为。

这里的问题是当一个文件被打开并且文件中有一个 BOM 标记时,它通常会被当前安装的本地文件从文件中读取。 因此position pointer不再位于文件的开头,我们有未定义的行为。

为了确保您的本地设置正确,您必须在打开文件之前进行设置。

std::fstream f;
f.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t>));

std::string path("path.txt");
f.open(path);

std::string lcpath;
f >> lcpath;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM