#include <iostream>
#include <string>
void reverseString(std::string& str) {
int start = 0;
int end = str.length() - 1;
while (start < end) {
std::swap(str[start], str[end]);
start++;
end--;
}
}
int main() {
std::string inputString;
std::cout << "Enter a string: ";
std::getline(std::cin, inputString);
reverseString(inputString);
std::cout << "Reversed string: " << inputString << std::endl;
return 0;
}
- Include necessary headers:
iostream
and string
. - Define a function
reverseString
that takes a reference to a string and reverses it in-place. - Initialize variables
start
and end
to the beginning and end indices of the string, respectively. - Use a
while
loop to swap characters from the start and end of the string until start
is no longer less than end
. - In the loop, swap the characters at the
start
and end
indices using std::swap
. - Increment
start
and decrement end
after each swap. - In the
main
function, declare a string variable inputString
. - Prompt the user to enter a string using
std::getline
. - Call the
reverseString
function to reverse the entered string. - Print the reversed string using
std::cout
.