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

前端 未结 6 1613
别跟我提以往
别跟我提以往 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:32

    @Lokno already provided you with the correct answer. However, let me nitpick your code a bit more to show you some other alternatives and to correct some minor mistakes.

    First, you didn't actually post a compiling example, because you forgot to show the included headers and and also didn't show the using namespace std; that was implicit in your code.

    Second, for the regular for loop, prefer to keep the loop variable inside the loop, unless you actually need to use it as a return value. Also prefer pre-increment ++i over post-increment i++. Furthermore, because you have made sure of the correct loop indices, there is no reason to use the bounds-checked element access at() over the unchecked [] version.

    In C++11, you have the range-for loop which allows for even shorter and more fool-proof code, where I also used auto where you could have used char. Unfortunately, there is no reverse range-for loop. The correct index-based reverse for loop is probably easier to read if you use i >= 0 rather than i > -1.

    Then there is an algorithm based loop using std::copy where you use the iterator interface of std::string (in particular the reverse iterators rbegin() and rend()) to copy each character through an ostream_iterator that is bound to standard output.

    BTW, I used the separator "|" rather than the newline to see stuff more easier, adapt to your taste. In any case, using std::endl can have performance implications because it flushes the output buffer every time.

    #include 
    #include 
    #include  // you forgot this
    #include    // you forgot this
    
    int main()
    {
        using namespace std;    // you forgot this
    
        // let's pretend this is the string
        string myAnimal = "Please enter the name of your favorite animal.";
    
        // keep the loop variable local, prefer pre-increment
        for (int i = 0; i < myAnimal.length(); ++i)
            cout << myAnimal[i] << "|";    // prefer [] over at()
        std::cout << "\n";
    
        // C++11 range-for
        for (auto c : myAnimal)
            std::cout << c << "|";
        std::cout << "\n";
    
        // index-based reverse loop
        for (int i = myAnimal.length() - 1; i >= 0; --i)
            cout << myAnimal[i] << "|";
        std::cout << "\n";
    
        // algorithm-based reverse loop
        std::copy(myAnimal.rbegin(), myAnimal.rend(), ostream_iterator(cout, "|"));
        std::cout << "\n";
    
        // main implicitly return 0
    }
    

    Live Example. PS: main() implicitly returns 0 upon success.

提交回复
热议问题