Write a program in c++ that reverses the C-style string pointed to by s. * * @pa
ID: 3603548 • Letter: W
Question
Write a program in c++ that reverses the C-style string pointed to by s.
*
* @param s a pointer to the character in a C-style string.
*
* NOTE: for this assignment, you can only use ++, --,
* = (assignment), ==,!= (comparison) and pointer subtraction
* (p1 - p2). You cannot use pointer arithmetic (s + i), or
* array notation (s[i]). In fact, you cannot have ANY integer
* variables or literals in your code. You also cannot use ANY
* standard library functions including strlen.
cpp file:
#include <string>
using namespace std;
#include "h27.h"
void reverse(char * s)
{
// Add your code here
}
This is the implementation file:
#ifndef H27_H_
#define H27_H_
void reverse(char * s);
#endif
// DO NOT CHANGE ANY OF THESE LINES
#define strlen(s) static_assert(false, "strlen not allowed");
#define strcat(d, s) static_assert(false, "strcat not allowed");
#define strcpy(d, s) static_assert(false, "strcpy not allowed");
#define string static_assert(false, "string not allowed");
Can someone do this and explain your steps please? Thanks.
Explanation / Answer
Solution:
reverse.cpp:
#include <string>
#include <iostream>
using namespace std;
#include "h27.h"
void reverse(char *s)
{
//initially two temporary pointers are teken
char *pointer1 = s;
char *pointer2 = s;
//moving the first pointer till null charcter found(cstring ends with null charcter)
while(*pointer1!=''){
pointer1++;
}
//decreasing one postion back.so pointer1 is present at last charcter of the cstring
pointer1--;
/**
*
* here swaping the first charcter and last charcter
* then we are moving pointer1 backward pointer2 forward
* till both are colide.when collision occurs pointer1>pointer2 condition fails
* Then loop will break.And string is reversed
*
* */
while(pointer1>pointer2){
char temp = *pointer2;
*pointer2 = *pointer1;
*pointer1 = temp;
pointer2++;
pointer1--;
}
//here we are printing the string
cout << "Reverse of given string is:" << s << endl;
}
int main(){
//here 2 charcter arrays are taken to test the reverse function
char cstring[] = {'H','e','l','l','o',''};
char cstring1[] = {'H','e','l','l',''};
//calling the reverse function
reverse(cstring);
reverse(cstring1);
return 0;
}
h27.h:
#ifndef H27_H_
#define H27_H_
void reverse(char * s);
#endif
// DO NOT CHANGE ANY OF THESE LINES
#define strlen(s) static_assert(false, "strlen not allowed");
#define strcat(d, s) static_assert(false, "strcat not allowed");
#define strcpy(d, s) static_assert(false, "strcpy not allowed");
#define string static_assert(false, "string not allowed");
sample output:
Reverse of given string is:olleH
Reverse of given string is:lleH
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.