【问题标题】:How do I both store unicode characters and output them to a file?如何存储 unicode 字符并将它们输出到文件?
【发布时间】:2020-06-07 19:07:38
【问题描述】:

这是我的输入函数:

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';

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

先生,¿Cómo va todo?

文件输出:

我的先生,——你要做什么?

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

【问题讨论】:

    标签: c++ windows unicode localization c++17


    【解决方案1】:

    如果您使用的是 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 编译的。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-03
        • 2013-09-25
        • 2017-10-07
        • 2021-12-03
        相关资源
        最近更新 更多