Write a program that inputs a C-String from the user and then reverses the conte
ID: 3539535 • Letter: W
Question
Write a program that inputs a C-String from the user and then reverses the contents of the string. Your program should work by using 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.
Template:
#include <iostream>
#include <cstdlib>
#include <cstring>
int main()
{
char myStr[80];
char temp;
char *head = NULL, *tail = NULL;
std::cout << "Enter a string less than 80 characters long." << std::endl;
cin.getline(myStr,80);
/* Assign myStr to both head and tail. Be cognizant to the position of each, especially tail in order to avoid pointing to the portion of the string. */
// *** Your code here ***
/* Write a while loop to reverse the string */
while (// *** Your code here ***)
{
// *** Your code here ***
} // end while
std::cout << "Your string reversed is :" << myStr << std::endl;
return 0;
} // end main
Tips:
1. Use strlen to calculate the address of the last character in the string. Loop until head >= tail. Use cin.getline to input a C-String.
Explanation / Answer
#include<iostream>
#include<string>
using namespace std;
int main() {
string str;
char *head, *tail, *cstr;
int i = 0;
cout << "Enter a string: ";
getline(cin, str);
cstr = new char[str.size() + 1];
strcpy_s(cstr, str.c_str());
head = &cstr[0];
tail = &cstr[str.size() - 1];
cout << "String inverted is: ";
char temp;
while (head <= tail) // this should be done only halfway of string and not for complete string, as you are swapping them now.
{
temp = cstr[i];
cstr[i] = *tail;
*tail = temp;
*tail--;
*head++;
i++;
}
cout << cstr;
cout <<" ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.