我相信輸出與UTF有關,但我不知道如何。 有人請解釋一下嗎?std :: string :: size()奇怪的行爲
#include <iostream>
#include <cstdint>
#include <iomanip>
#include <string>
int main()
{
std::cout << "sizeof(char) = " << sizeof(char) << std::endl;
std::cout << "sizeof(std::string::value_type) = " << sizeof(std::string::value_type) << std::endl;
std::string _s1 ("abcde");
std::cout << "s1 = " << _s1 << ", _s1.size() = " << _s1.size() << std::endl;
std::string _s2 ("abcdé");
std::cout << "s2 = " << _s2 << ", _s2.size() = " << _s2.size() << std::endl;
return 0;
}
輸出是:
sizeof(char) = 1
sizeof(std::string::value_type) = 1
s1 = abcde, _s1.size() = 5
s2 = abcdé, _s2.size() = 6
g++ --version
打印g++ (Ubuntu 5.4.0-6ubuntu1~16.04.1) 5.4.0 20160609
QTCreator
編譯如下:
g++ -c -m32 -pipe -g -std=c++0x -Wall -W -fPIC -I../strsize -I. -I../../Qt/5.5/gcc/mkspecs/linux-g++-32 -o main.o ../strsize/main.cpp
g++ -m32 -Wl,-rpath,/home/rodrigo/Qt/5.5/gcc -o strsize main.o
非常感謝!
試着打印'sizeof('é')',看看你得到了什麼。 – Peter
感謝您的時間。 我添加以下兩行: '的std :: COUT << 「的sizeof( 'E')=」 <<的sizeof( 'E')<<的std :: ENDL;' '的std :: COUT < < 「的sizeof(\」 é\ 「)=」 <<的sizeof( 「E」)<<的std :: ENDL;' 和輸出是: '的sizeof( 'E')= 4' ' sizeof('é')= 3' – canellas
@canellas'sizeof('é')'很可能會將'char'提升爲'int',這可以解釋爲什麼它的大小是4.字符串文字「é」是與'const char []'等價,所以'sizeof(「é」)'是3,因爲'é'是用UTF-8(0xC3 0xA9)中的2個char編碼的,後面是空終止符。 –