4
#include<iostream> #include<string> using namespace std; int main(){ string i = "abc\0defg"; cout<<i<<endl; // This prints "abc" string x = "abcdefg"; x[3]='\0'; cout << x << endl; // This prints "abcefg" } 

I know that the instance i of the C++ String class doesn't interpret \0 as the end of a string. Why the string i left out everything after the \0? What's the difference between string i and x?

1

1 Answer 1

6

The string literal "abc\0defg" is a char const [9]. std::string doesn't have a constructor that takes an array, but it can accept a char const *. So when i is used with that constructor, it thinks that the \0 inside the string indicates the end of the string (which is in fact how the end of a char const * string is usually calculated). So i only contains abc when it is constructed.

Sign up to request clarification or add additional context in comments.

11 Comments

If you want to add fun/confusion (depending on your point of view), throw in using namespace std::string_literals; and put an s at the end of the initialization, as in string i = "abc\0defg"s;. :)
When this array is decayed to a char const *, it only contains abc. Hmm. I would say it a bit more convoluted: A char const* is a pointer and it points to the address where 'a' is stored. abc\0defg\0 will still be there but (practically) every standard C string function will stop at the first \0 (after c) if there is no option to provide the explicit length as additional argument.
...and this is what happens in std::string::string(const char*) as well. Please, note that there is also a std::string::string(const char*, size_t) which could be used instead: const char str[] = "abc\0defg"; string i(str, sizeof str - 1); (The - 1 is given to cut of the second \0.)
@MohitSharma That's just how strings are printed. The \0 is not considered the end of the string.
@MohitSharma You might want to try the code in the question, then change cout << x << endl; to cout << x.c_str() << endl;. If it were not for the null character, streaming a string would have the same result as streaming its c_str().
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.