Why is the zero termination ignored when I assign it after initializing the string?

100 Views Asked by At

I arrived at two different cases but was not able to arrive at a conclusion that what was actually happening inside. Can anyone please explain?

CASE 1:

#include<iostream>
using namespace std;
int main() {
string my_string = "This is a sam\0ple text"; //check the \0
cout << my_string;
return 0;
}

OUTPUT:

This is a sam

CASE 2:

#include<iostream>
using namespace std;
int main() {
string my_string = "This is a sample text"; 
my_string[13]='\0';
cout << my_string;
return 0;
}

OUTPUT:

This is a sam le text

I thought these two cases are similar and hence the output should come out to be the same but actually this is what was happening. Please explain.

0

There are 0 best solutions below