0

I am writing a function for a class to reverse a string using recursion. I have a semi-functioning piece of code but it has an issue where it drops the last character to be printed on screen. It has to use the prototype "void reverse(string & letters);" so I can only take one input. It's probably a simple fix, but I can't see what's going wrong.

void reverse(string & letters){

  if (letters.size() == 0){
    return;
  }
  string t = letters.substr(1);
  reverse(t);
  cout << letters[0]; 
}

Input examples - Like / giant Output examples - eki / tnai

  • It's working fine for me, could you let us know what compiler you are using, and a complete working example (with the `main`) part as well? – ShadowMitia Oct 31 '21 at 20:43
  • 2
    Is your requirement to change the passed string so the caller can use it, or is it to print it in reverse? Your description implies changing the string passed, but your implementation seems to be (trying to) the print in reverse without modifying the string – Peter Oct 31 '21 at 20:44
  • @ShadowMitia I just checked my main and I found that it cin.ignore was deleting the first character... Thanks for the help, although I think Peter is right in saying that it should modify the original string (although the professors instructions are really vague). I'll keep working at it. – Ian Rogers Oct 31 '21 at 20:50
  • Don't use cin.ignore before reading input - instead always use it after statements that you KNOW leave stuff in the buffer Calling cin.ignore ignores one character but what if the user hit space before they pressed enter - then you need to ignore two. So maybe you should use `cin.ignore(numeric_limits::max(), '\n')` More info at https://stackoverflow.com/questions/25020129/cin-ignorenumeric-limitsstreamsizemax-n – Jerry Jeremiah Oct 31 '21 at 20:53
  • @Peter The assignment is to assign the reversed word to the passed string. I assume I can use one of the string functions to replace characters in "letters" instead of "cout << letters[0]"? – Ian Rogers Oct 31 '21 at 21:43
  • It’s a one-liner if you use the provided reverse iterators and proper constructor call. – sweenish Oct 31 '21 at 22:34
  • 2
    Does this answer your question? [Write a recursive function that reverses the input string](https://stackoverflow.com/questions/5760774/write-a-recursive-function-that-reverses-the-input-string) – Alaa Mahran Nov 01 '21 at 00:15

0 Answers0