What does '\0' mean?

后端 未结 6 1707
梦如初夏
梦如初夏 2020-12-29 05:55

I can\'t understand what the \'\\0\' in the two different place mean in the following code:

string x = \"hhhdef\\n\";
cout << x << endl;
x[3]=\'\         


        
6条回答
  •  余生分开走
    2020-12-29 06:27

    C++ std::strings are "counted" strings - i.e., their length is stored as an integer, and they can contain any character. When you replace the third character with a \0 nothing special happens - it's printed as if it was any other character (in particular, your console simply ignores it).

    In the last line, instead, you are printing a C string, whose end is determined by the first \0 that is found. In such a case, cout goes on printing characters until it finds a \0, which, in your case, is after the third h.

提交回复
热议问题