Skip to main content
added 5 characters in body
Source Link
P0W
  • 48.1k
  • 9
  • 78
  • 124

std::string constructor that takes a const char* assumes the input is a C string. C strings are '\0' terminated and thus stops when it reaches the '\0' character.

If you really want to play you need to use the constructor that builds the string from a char array (not a C-String).

STL sequence containers allocate sizes internally, unless specified.exceed the amount required to store automatically

Example :

int main () { string s="Elephant"; s[4] ='\0'; //C++ std::string is NOT '\0' terminated cout<<s<<endl; //Elep ant string x("xy\0ab"); // C-String assumed. cout<<x; //xy return 0; } 

std::string constructor that takes a const char* assumes the input is a C string. C strings are '\0' terminated and thus stops when it reaches the '\0' character.

If you really want to play you need to use the constructor that builds the string from a char array (not a C-String).

STL sequence containers allocate sizes internally, unless specified.

Example :

int main () { string s="Elephant"; s[4] ='\0'; //C++ std::string is NOT '\0' terminated cout<<s<<endl; //Elep ant string x("xy\0ab"); // C-String assumed. cout<<x; //xy return 0; } 

std::string constructor that takes a const char* assumes the input is a C string. C strings are '\0' terminated and thus stops when it reaches the '\0' character.

If you really want to play you need to use the constructor that builds the string from a char array (not a C-String).

STL sequence containers exceed the amount required to store automatically

Example :

int main () { string s="Elephant"; s[4] ='\0'; //C++ std::string is NOT '\0' terminated cout<<s<<endl; //Elep ant string x("xy\0ab"); // C-String assumed. cout<<x; //xy return 0; } 
Source Link
P0W
  • 48.1k
  • 9
  • 78
  • 124

std::string constructor that takes a const char* assumes the input is a C string. C strings are '\0' terminated and thus stops when it reaches the '\0' character.

If you really want to play you need to use the constructor that builds the string from a char array (not a C-String).

STL sequence containers allocate sizes internally, unless specified.

Example :

int main () { string s="Elephant"; s[4] ='\0'; //C++ std::string is NOT '\0' terminated cout<<s<<endl; //Elep ant string x("xy\0ab"); // C-String assumed. cout<<x; //xy return 0; }