I am new with strings in C++. I am just confused with the working of the code below (used to reverse a string).
std:: string rev;
for(int i= str.size()-1; i>=0; --i)
{
rev.push_back(str[i]);
}
std:: cout<<" Reversed= "<<rev<<endl;
The Problem is that the last character of a string is null character '\0'
. So, when the loop runs for the first iteration, it should place a null character at the start of rev
and one more thing, here the string rev
may not be null terminated because '\0'
is not assigned as the last character of string.
But when I execute the Program, it works fine. I know I am wrong while thinking all this. Can anyone explain the working please? I shall be glad and Thankful to you :)