I am trying to reverse a string using head() (first letter of a string) and tail() (all letters after the head) functions from a class I wrote. Everything is working alright except my output's not quite how I wanted it. For example, I input abcde, I should get edcba but this is what I get: edecdebcdea. as you can see it reverses it but still takes in all letters after the head (except for the original head):
E De Cde Bcd de A. I'm new to recursion so I find this very confusing, any help would be appreciated. Thanks
example output:
Here's the recursive function, I'm pretty sure the problem's somewhere in here:Code:Enter a string: abcde x: abcde x: bcde x: cde x: de x: e x: mystring: edecdebcdea
relevant member functions from my class "strings"Code:strings reverse(strings x) { cout<< "x: " <<x<<endl; //test output if (x.stringlength() <= 0) { return x; } return reverse(x.tail()) + x.head(); //recursive statement }
Code:/********************************************************************** * Default Constructor: **********************************************************************/ strings::strings() { int index = 0; while (index < 20) { strhead[index] = '\0'; strtail[index] = 't'; fullstring[index] = 'f'; index++; } head(); tail(); } /********************************************************************** * return string head **********************************************************************/ char *strings::head() { strncpy(strhead, fullstring, 1); return strhead; } /********************************************************************** * Return string tail **********************************************************************/ strings strings::tail() { int index = 0; strcpy(strtail, fullstring); //Test for null terminator while (fullstring[index] != '\0') { strtail[index] = fullstring[index + 1]; index++; } return strtail; } /********************************************************************** *Return length of string **********************************************************************/ int strings::stringlength() { return strlen(fullstring); } /********************************************************************** * Overloaded + operator **********************************************************************/ strings strings::operator +(char right[1]) { strcat(fullstring, right); return fullstring; } /********************************************************************** * Overloaded = operator **********************************************************************/ void strings::operator =(const strings &right) { strcpy(fullstring, right.fullstring); }



LinkBack URL
About LinkBacks



