Understanding C string characteristics
suggest change#include <cstring>
#include <iostream>
#include <string>
int main()
{
const char * C_String = "This is a line of text w";
const char * C_Problem_String = "This is a line of text ኚ";
std::string Std_String("This is a second line of text w");
std::string Std_Problem_String("This is a second line of ϯϵxϯ ኚ");
std::cout << "String Length: " << Std_String.length() << '\n';
std::cout << "String Length: " << Std_Problem_String.length() << '\n';
std::cout << "CString Length: " << std::strlen(C_String) << '\n';
std::cout << "CString Length: " << std::strlen(C_Problem_String) << '\n';
return 0;
}
Depending on platform (windows, OSX, etc) and compiler (GCC, MSVC, etc), this program may fail to compile, display different values, or display the same values.
Example output under the Microsoft MSVC compiler:
String Length: 31
String Length: 31
CString Length: 24
CString Length: 24
Under this MSVC run, std::string::length and strlen match for the plain strings and the strings that contain ኚ, ϯ, and ϵ. Both functions count char elements, not readable characters. Equal lengths mean each of those source characters occupied one char in that build’s execution encoding. They were not stored as several Unicode code units in those strings.
Under the GNU/GCC compiler the program output is:
String Length: 31
String Length: 36
CString Length: 24
CString Length: 26
This example demonstrates that the GCC compiler used on this Linux platform accepts these characters and encodes them as more than one byte. length() and strlen still report the number of char elements. Here that is a byte count, not the number of readable characters.
These differences are due to how international languages are handled on a per-platform basis - and more importantly, that the C and C++ strings used in this example can be considered an array of bytes, such that (for this usage) the C++ language considers a character (char) to be a single byte.