How to output a string in reverse order in C++?

In C++, you can reverse the input string by using a loop. Here is an example code:

#include <iostream>
#include <string>

int main() {
    std::string input;
    std::cout << "请输入一个字符串: ";
    std::getline(std::cin, input);

    std::cout << "反向输出字符串: ";
    for (int i = input.length() - 1; i >= 0; i--) {
        std::cout << input[i];
    }
    
    return 0;
}

In the above code, the user’s input is first retrieved using the std::getline() function and stored in the input variable. Then, by looping through the input string from the end, each character is outputted to the console one by one, achieving reverse output of the string.

bannerAds