Does std :: string really contain a null character '\ 0' not at the end?

Consider the following code:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s = "Allie has a cat.";
    s[3] = '\0';
    cout << s << '\n';
    return 0;
}

      

Is this code valid? Are there any pitfalls that will invalidate it if, in addition to the above, we do some other operations on it string

?

  • In C, the character was '\0'

    used as a line terminator. std::string

    still seems to be following this tradition
    . Therefore, it would be unreasonable to assume that under certain circumstances, being premature '\0'

    can break practices such as std::string::size()

    .
  • It would be unreasonable to assume that some subroutines of the type cout

    might use the base std::string::c_str()

    for their operation, perhaps inject some UB when that null-terminated string is "early terminated".

But suppose, as on ideone , cout

this std::string

works fine and prints:

Alle has a cat.

      

Ive compiled and ran this program locally and confirmed that it prints 0x00

between l

and e

. Is it valid to print blank characters to the console? Do text files really contain null characters? gedit

refuses to open the file to which the output of this program was redirected.

+3


source to share





All Articles