【发布时间】:2020-09-10 14:59:25
【问题描述】:
我正在学习 wstrings,因为我想了解一个项目的 UTF-8。我做了一个简单的程序来测试使用 wstrings 的操作:
int main()
{
std::wstring test;
std::wstring test2;
std::wstring test3;
int n;
getline(std::wcin, test);
std::wcout << "\n" << test;
for (n = 0; n < test.size(); n++)
{
test[n] += n * n;
test2[n] = test[n];
}
std::wcout << test2 << "\n";
for (n = 0; n < test2.size(); n++)
{
test2[n] -= n * n;
test3[n] = test[n];
}
std::wcout << test3 << "\n";
return 0;
}
当我执行它时,我得到这个错误:“字符串下标超出范围”
这是我的第一个 C++“严肃”项目,感谢任何帮助!
【问题讨论】:
-
请注意
std::wstrings和utf-8不太可能相关,例如在 Windows 上std::wstring是utf-16编码 -
真的吗?我实际上有点迷失了。我认为我需要 wstrings,因为由于某种原因,当我使用 std::string 时,test2 和 test3 中的字符不会通过 Unicode 字符的 0 - 255 部分。谢谢你的信息。
-
是的,您应该在 c++20 中使用
std::u8string或在存储 utf-8 之前使用std::stringen.cppreference.com/w/cpp/string/basic_string -
@GuilhermeGaldino
std::wstring使用wchar_t元素,在 Windows 上为 2 个字节,在其他平台上为 4 个字节。所以std::wstring在 Windows 上是 UTF-16 编码的,在其他平台上是 UTF-32 编码的。std::string使用char元素,在所有平台上都是 1 字节大小。在 C++20 之前,std::string可以保存 UTF-8 编码的字符串。 C++20 为此添加了char8_t和std::u8string。任何 UTF 编码的字符串都可以处理整个 Unicode。但大多数 Windows API 函数只喜欢本地 ANSI 或 UTF-16 字符串。
标签: c++ visual-c++ c++17 wstring