如何存储 unicode 字符并将其输出到文件?

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

本文关键字:输出 文件 字符 何存储 存储 unicode      更新时间:2023-10-16

这是我的输入函数:

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上编码。

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

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