344. Reverse String c++

To reverse a string in C++, you can follow these steps:

  1. Include the necessary header file: #include <iostream>

  2. Declare the main function: int main()

  3. Declare a string variable to store the input: std::string str;

  4. Prompt the user to enter a string: std::cout << "Enter a string: ";

  5. Read the input string from the user: std::cin >> str;

  6. Declare a variable to store the length of the string: int length = str.length();

  7. Use a for loop to iterate through each character in the string: for (int i = length - 1; i >= 0; i--)

  8. Inside the loop, print each character in reverse order: std::cout << str[i];

  9. End the loop and the program.

Here is the complete code:

#include <iostream>

int main() {
    std::string str;
    std::cout << "Enter a string: ";
    std::cin >> str;
    int length = str.length();
    for (int i = length - 1; i >= 0; i--) {
        std::cout << str[i];
    }
    return 0;
}

This code will prompt the user to enter a string, and then it will print the string in reverse order.