std::wofstream 运算符<< 未按预期工作

std::wofstream operator<< not working as expected

本文关键字:lt 工作 wofstream std 运算符      更新时间:2023-10-16

我是Visual Studio 2015用户,正试图编写以下函数:

void saveWordsToFile(const std::string& filename, const std::vector<std::pair<std::wstring, std::wstring>>& words)
{
    std::wofstream fs(filename, std::ios::out | std::ios::app);
    if (fs.fail()) throw std::runtime_error("loadTextFromFile -> Failed to open '" + filename + "'!");
    for (auto& word : words) fs << word.first << " " << word.second << std::endl;
    fs.close();
}
int main()
{
    std::vector<std::pair<std::wstring, std::wstring>> words;
    words.push_back({ L"1", L"green" });
    words.push_back({ L"ż", L"yellow" });
    words.push_back({ L"3", L"purple" });
    saveWordsToFile("database.txt", words);
    return 0;
}

文件database.txt在程序执行之前是这样的:

0 test

执行后,我期待:

0 test
1 green
ż yellow
3 purple

然而我得到了:

0 test
1 green

很容易看出,字符"ż"是一个问题的原因,但我需要使用它,如何获得正确的输出?

在我的系统中,流试图使用wcrtombL'ż'转换为字节流,但转换失败(可能是由于区域设置问题?)。

此时,流以fs.bad()返回true结束,并且跳过任何进一步的输出。