Write a program that inputs a C-string from the user and then reverses the conte
ID: 3816667 • Letter: W
Question
Write a program that inputs a C-string from the user and then reverses the contents of the string. Your program MUST use at least two pointers. The "head" pointer should be set to the address of the first character in the string, and the "tail" pointer should be set to the address of the last character in the string (i.e. the character before the terminating null). The program should swap the characters referenced by these pointers increment "head" to point to the next character, decrement "tail" to point to the second to last character, and so on, until all characters have been swapped and the entire string reversed.Explanation / Answer
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main() {
string input;
char *head = new char, *tail = new char;
char temp;
cout << "Enter in a string that you want reversed: ";
getline(cin, input);
char arr[input.length()];
strcpy(arr, input.c_str());
head = &arr[0]; tail = &arr[input.length()-1];
for(int i=0; i<input.length()/2; i++)
{
temp = *(tail);
*tail = *head;
*head = temp;
tail --; head ++;
}
for(int i=0; i<input.length(); i++) {
cout << arr[i];
}
//Free up memory
delete head; delete tail;
head = NULL; tail = NULL;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.