<分区>
考虑
#include <string>
#include <iostream>
int main()
{
std::string test="αλφα";
std::cout << "size() of '" << test << "' = " << test.size() << std::endl;
}
产生
size() of 'αλφα' = 8
我如何使用 C++ 标准库找到通过写入字符串(即上例中的 4)生成的输出宽度?
<分区>
考虑
#include <string>
#include <iostream>
int main()
{
std::string test="αλφα";
std::cout << "size() of '" << test << "' = " << test.size() << std::endl;
}
产生
size() of 'αλφα' = 8
我如何使用 C++ 标准库找到通过写入字符串(即上例中的 4)生成的输出宽度?
最佳答案
这里的问题与字符串相关的编码有关。
这对我来说看起来像 UTF-8 编码(第一个字符不是小写字母 'a'
)。在该编码中,您提供的字符每个占用两个字节,用于解释答案。
UTF-8 编码得到了 C++11 标准的广泛支持(相当优雅,UTF-8 在任何文本流中都没有任何零字节 cf. Windows Unicode)——您可以使用std::string
虽然长度通常会被低估 - 但在编辑器中直接创建该类型的字符串文字时必须小心。
从这里阅读更多内容:How to use Unicode (UTF-8) in C++
关于c++ - 如何获取字符串输出的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54350928/