Simply print the string backwards This code is very, very simple, but I was wondering how it could be improved:

#include &lt;iostream&gt;

int main() {
    std::string input;
    std::getline(std::cin, input);

    for(int i = 1; i &lt;= input.length(); i++){
        std::cout &lt;&lt; input[input.length() - i];
    }

    std::cout &lt;&lt; '\n';
    return 0;
}


This code takes a string input, and prints it backwards. For example:

This will be printed backwards.


Becomes:

.sdrawkcab detnirp eb lliw sihT


Given the simplicity of this code, is there a way to optimize it? I understand that since it is very short, it will run fast no matter what. However, I hate inefficiencies in code, and I want to help improve the way that I write code.

This is related to, but not copied directly from, this SO answer. (I only found this SO answer after writing the code)
One simple improvement would be to restructure the for() loop:

for(int i = input.length() - 1; i &gt;= 0; --i){
    std::cout &lt;&lt; input[i];
}


A simple decrement operation might lead to more efficient machine code than calculating input.length() - i in every iteration.



Another improvement would be to use a more c++-ish way. But that means to change the string itself:

 std::getline(std::cin,input);
 std::reverse(std::begin(input),std::end(input));
 std::cout &lt;&lt; input &lt;&lt; '\n';




Or using the reverse iterators in the loop:

 for(auto it = input.rbegin(); it != input.rend(); ++it) {
      std::cout &lt;&lt; *it;
 }




As I've mentioned in my comment, the most generic (and c++stylish) way to achieve that is to write your own adapter to achieve iterating a sequence in the reverse order. So I'm citing that solution here:


 // -------------------------------------------------------------------
 // --- Reversed iterable
 using namespace std; // for rbegin() and rend()

 template &lt;typename T&gt;
 struct reversion_wrapper { T&amp; iterable; };

 template &lt;typename T&gt;
 auto begin (reversion_wrapper&lt;T&gt; w) { return rbegin(w.iterable); }

 template &lt;typename T&gt;
 auto end (reversion_wrapper&lt;T&gt; w) { return rend(w.iterable); }

 template &lt;typename T&gt;
 reversion_wrapper&lt;T&gt; reverse (T&amp;&amp; iterable) { return { iterable }; }



Above taken from here.