How does Null character behaves in Std::string

In this question we have to ROTATE a string by 4 characters
Input: coding blocks
Excepted output: ockscoding bl
The actual output I am getting is: ockscoding bl cks

My question is why string is getting printed even after NULL character
#include
#include

using namespace std;

string rotate(string &ptr,int k)
{
int i=ptr.length();

ptr.resize(i+k,'$');
//cout<<ptr<<endl;

while(i>=0)
{
	ptr[i+k]=ptr[i];  // scanning backwards and shifting each char forward
	i--;
}
//cout<<ptr<<endl;

 i=ptr.length();

//cout<<i<<endl;

 int j=i-k;
 int s=0;

 while(j<i)
 {
 	ptr[s]=ptr[j]; //placing the char from required position
 	s++;
 	j++;
 }
 ptr[i-k]='\0'; // INULL character is placed in the string

 return ptr;

}

int main()
{
int k=4;
string str;
getline(cin,str);

cout<<"original string="<<str<<endl;

rotate(str,k);

cout<<"after rotating="<<str<<endl;

}

Anyone explain logic behind this

I have made changes in your code by which you can get the required output.
https://ide.codingblocks.com/s/36204

You need to stop iterating the string when you encounter the null character. Even when you insert the null character in the string, it prints the complete string when using cout<<str

“Even when you insert the null character in the string, it prints the complete string when using cout<<str”

  1. Sir why is it so, doesn’t C++ treat NULL character as a terminator by default.
  2. aren’t C++ string NULL terminated (e.g string str=“pointer”)

Go through these articles. They will surely help you.

There are some things in programming which you come to know about only after experimenting on them…