C++ Printing a string in reverse using a for loop

前端 未结 6 1665
别跟我提以往
别跟我提以往 2021-01-25 12:13

I have a program that prints out the characters of a string using a for-loop. It must also print the same characters in reverse, which is where I\'m having problems. Can someone

6条回答
  •  耶瑟儿~
    2021-01-25 12:33

    You could use reverse iterators

    #include 
    #include 
    
    int main() {
      std::string myAnimal;
    
      std::cout << "Please enter the name of your favorite animal.\n";
      std::cin >> myAnimal;
    
      // Iterate in reverse order
      for(auto c = myAnimal.rbegin(); c != myAnimal.rend(); ++c) {
        std::cout << *c << std::endl;
      }
    }
    

    Note that you have to increment the variable 'c' (and not decrement it) since this is a reverse iterator.

提交回复
热议问题