Interpretation of '\0' in C++

Viewed 113
#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 Answers

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.

Related