344. Reverse String c++
To reverse a string in C++, you can follow these steps:
Include the necessary header file:
#include <iostream>
Declare the main function:
int main()
Declare a string variable to store the input:
std::string str;
Prompt the user to enter a string:
std::cout << "Enter a string: ";
Read the input string from the user:
std::cin >> str;
Declare a variable to store the length of the string:
int length = str.length();
Use a for loop to iterate through each character in the string:
for (int i = length - 1; i >= 0; i--)
Inside the loop, print each character in reverse order:
std::cout << str[i];
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.