The code is effectively swapping the characters on opposite sides of the string. The first and last are swapped, then second and second-to-last, then third and third-to-last, and so on until it gets to the middle of the string (and thats where the divide-by-two comes in).
Its looks a bit convoluted. A more readable version would be this:
#include <iostream>
int main()
{
std::cout << "Enter a string: ";
std::string line;
std::getline(std::cin, line);
int i = 0; // set i to index 0
int j = line.size()-1; // set j to final index of line
while (i <= j) // until i and j have not crossed over
{
std::swap(line[i], line[j]); // swap elements at index i and j
i++; // move i forward
j--; // move j back
}
std::cout << "Line reversed is: " << line << "\n";
}
@zifi: Maybe not, but in a quick demo like this its no big deal.
@Sakurawhatever: When you were a beginner, did you go straight to STL functions? Or did you actually try learning the logic and code that these STL functions based on?Calling std::reverse() gives a beginner no information or understanding as to how the string is reversed.
@Arslanwhatever: Unless the teacher forbids him to use it, there is no reason why we should not use std::reverse(). It makes our code looks neater and more self-documenting.
@Sakurawhatever: You are missing the point. The OP is clearly trying the understand the code (which reverses a string). What good of an answer is "just use std::reverse() bro" ?
Or maybe I should have answered with "send me a private message", lol.