-1

I'm trying to reverse a string (e.g change "bro" to "orb") using iterators. Unfortunately, my code doesn't work. Here's my code:


for(std::string text; std::cin >> text;){
    for(std::string::const_iterator it = text.cend() + 1; it <= text.cbegin(); --it)
        std::cout << *it;
}


return 0;}

Where did I go wrong?

1 Answers1

2

Firstly your code isn't reversing a string, it's printing a string backwards. Not the same thing at all.

The easy way to print a string backwards would be to use a reverse iterator

for (auto it = text.rbegin(); it != text.rend(); ++it)
    std::cout << *it;

But if you want to do it with a regular iterator then the following works

auto it = text.end();
while (it > text.begin())
     std::cout << *--it;
john
  • 71,156
  • 4
  • 49
  • 68
  • 1
    and what does the arrow operator ```-- >``` do? – KnowledgeSeeker Jan 17 '21 at 13:21
  • 1
    @KnowledgeSeeker Well I changed that but it was only a combination of post decrement `--` and greater than `>`. – john Jan 17 '21 at 13:22
  • 1
    @KnowledgeSeeker That's the one of the most famous C++ question on StackOverflow :)) https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c – adembudak Jan 17 '21 at 14:02