/*
* @topic T0M295 Reverse string demo
* @brief Reverse characters doing almost everything from scratch
*/
#include <iostream>
#include <cstdlib>
#include <string>
#include <algorithm>
using namespace std;
// get characters and store them in memory buffer
// pstr is the pointer to the memory buffer
// max_size specifies the buffer size
void get_input( char* pstr, int max_size )
{
char ch;
char* stop_here = pstr + max_size;
for (; pstr < stop_here && cin.get(ch); ++pstr) {
if ( ch == '\n' ) {
// user pressed the enter key
// terminate user input by null character:
*pstr = '\x0';
return;
}
*pstr = ch;
}
}//get_input
// swap two characters in memory
void custom_swap( char * pleft, char * pright )
{
char temp = *pleft;
*pleft = *pright;
*pright = temp;
}//custom_swap
// reverse characters in the memory buffer
void custom_reverse( char* pstr )
{
// pstr -> ABCDEF\0
// ^ ^
// | |
// p1 p2
char * p1 = pstr;
char * p2 = pstr + strlen( pstr );
if ( p1 == p2 ) return; // do nothing if input is empty
--p2; // input is not empty, so it's safe to decrement p2
while ( p1 < p2 ) {
//swap( p1, p2 ); // BEWARE! this swaps the pointer addresses!
// swap( *p1, *p2 ); // using std::swap - use this
custom_swap( *p1, *p2 ); // custom swap for demo purposes
++p1;
--p2;
}
}//custom_reverse
int main()
{
for (;;) {
cout << "Enter text to reverse: ";
//string str;
const int ARRAY_SIZE = 1024;
char str[ ARRAY_SIZE ];
get_input( str, ARRAY_SIZE );
if ( !strncmp(str, "quit", ARRAY_SIZE ) ) {
break;
}
custom_reverse( str );
cout << "[" << str << "]\n";
}//forever
system( "pause" );
return 0;
}//main