SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Pointers And Dynamic Arrays
Exercise:
Programming Projects
Question:3 | ISBN:9780132846813 | Edition: 5

Question

Write a program that accepts a C-string input from the user and 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.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

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 (cstr, str.c_str());

	head = &cstr[0];
	tail = &cstr[str.size() - 1];

	cout << "Inverted is: ";

	char temp;
while (head <= tail)
{
		temp = cstr[i];
		cstr[i] = *tail;
		*tail = temp;
		*tail--;
		*head++;
		i++;
	}

	cout << cstr << endl;

	system("pause");
	return 0;
}

 

0 0

Discussions

Post the discussion to improve the above solution.