如何既存储 unicode 字符又将它们输出到文件?

How do I both store unicode characters and output them to a file?

这是我的输入函数:

template <typename T>
T getUserInput(std::string prompt = "")
{
    T input;
    std::cout << prompt;
    if constexpr (std::is_same_v<T, std::string>)
    {
        std::getline(std::cin, input);
    }
    else
    {
        std::cin >> input;
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return input;
}

我这样调用它并将其写入文件:

int main()
{
    setlocale(LC_ALL, "spanish");
    std::ofstream testfile{ "testfile.txt" };
    std::string test = getUserInput<std::string>("Please write a string: ");
    testfile << test << '\n';

但是,我会说西班牙语,所以有时我想写“á”、“ñ”、“¿”等字符,但它们被省略或无法识别。如果我写:

Mi señor, ¿Cómo va todo?

文件输出:

Mi se¤or, ¨C¢mo va todo?

正如您在我的代码中看到的那样,我已经尝试使用 setlocale 来设置西班牙语,只要我想通过 std::cout 手动输出这些字符,它就可以工作,但我无法存储它们。我也试过使用 std::wstring 而不是 std::string 但我无法让 getline 输出到它。我该怎么做?顺便说一下,我正在 Windows.

上编码

使用 std::wstring 和 std::wcin 从输入中获取 wchar 字符串 wcin

如果您使用 Windows,您可以使用 _setmode:

#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <string>
#include <fstream>


template <typename T>
T getUserInput(std::wstring prompt = "")
{
    T input;
    std::wcout << prompt;
    if constexpr (std::is_same_v<T, std::wstring>)
    {
        std::getline(std::wcin, input);
    }
    else
    {
        std::wcin >> input;
        std::wcin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return input;
}

int main()
{
    _setmode(_fileno(stdin), _O_WTEXT);
    _setmode(_fileno(stdout), _O_WTEXT);

    std::wofstream testfile{ "testfile.txt" };
    std::wstring test = getUserInput<std::wstring>(L"Please write a string: ");
    testfile << test << '\n';
}

注意这是用 MSVC 编译的。