Introduction
In programming, string manipulation is a common task. One of the most basic operations is reversing a given string. This operation is widely used in various applications such as palindromes checking, encryption algorithms, and other string processing tasks.
Objective
The objective of this program is to take an input string from the user and reverse it using C++. By the end of this exercise, you will understand how to manipulate strings, use loops, and implement basic C++ functions to solve simple problems.
Code
#include #include using namespace std; // Function to reverse the input string string reverseString(string str) { int n = str.length(); // Get the length of the string for(int i = 0; i < n / 2; i++) { // Swap characters from the beginning and end swap(str[i], str[n - i - 1]); } return str; // Return the reversed string } int main() { string inputString; // Prompt the user for input cout << "Enter a string to reverse: "; getline(cin, inputString); // Read the whole line including spaces // Call the function to reverse the string string reversedString = reverseString(inputString); // Display the reversed string cout << "Reversed string: " << reversedString << endl; return 0; }
Explanation of the Program
The program starts by including the necessary libraries:
- #include <iostream> – For input-output operations.
- #include <string> – For handling string data types in C++.
The reverseString() function accepts a string as input and reverses it. This is achieved by swapping characters from the beginning and the end of the string using a loop. The loop runs from the first character to the middle of the string (i.e., n / 2
iterations), and in each iteration, the characters at the current position i
and its corresponding position n - i - 1
are swapped.
The main() function does the following:
- It declares a string variable
inputString
to store the input from the user. - It prompts the user to enter a string and stores it using
getline(cin, inputString)
to handle spaces. - It calls the
reverseString()
function to reverse the string. - Finally, it prints the reversed string using
cout
.
How to Run the Program
To run the program, follow these steps:
- Write or paste the code into a C++ IDE or text editor (e.g., Code::Blocks, Visual Studio, or any online C++ compiler).
- Save the file with a .cpp extension (e.g., reverse_string.cpp).
- Compile the code using a C++ compiler.
- Run the executable file generated by the compiler.
- Input a string when prompted and the program will output the reversed string.
Sample Output
Enter a string to reverse: Hello World! Reversed string: !dlroW olleH