Home > front end >  C Program to Reverse String via Recursion keeps giving me an unwanted letter, but Python counterpa
C Program to Reverse String via Recursion keeps giving me an unwanted letter, but Python counterpa

Time:04-10

C Program (Wrong)

#include <iostream>
#include <string>

using namespace std;

char revstr(string s, int n){ //I cannot assign string here. Error pops up.
    if (n == 0){
        return s[0];
    }
    else
    {
        return s[n]   revstr(s, n-1);
    }
}

int main(){
    string sin;
    cin >> sin;
    int n = sin.length() - 1;
    cout << revstr(sin, n) << endl;
    return 0; 
}

Python Program (Correct)

def revstr(s, n):
    if n == 0:
        return l[0]
    else:
        return l[n]   revstr(s, n-1)

#Main Code
sin = input()
l = []

for i in range(0, len(sin)):
    l.append(sin[i])

print(l)
n = len(l) - 1
print(revstr(sin, n))

Description

I am trying to reverse a string using the recursion technique as classwork, but then my program works on Python but not C , which gives "O" only.

I do not know what the problem in the C program is, since the Python counterpart works well.

For example,

Input

Computer

C Output

O

Python Output

retupmoC

IMPORTANT

  1. Instructions said I have to do it in recursion
  2. This happens when I declare the function return value as string.
error: could not convert 's.std::__cxx11::basic_string<char>::operator[](0)' from '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' {aka 'char'} to 'std::string' {aka 'std::__cxx11::basic_string<char>'}
    8 |         return s[0];
      |                   ^
      |                   |
      |                   __gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type {aka char}   

CodePudding user response:

There are three problems I can see with the code:

  1. Check the return type of revstr - you want to return a full string, but it returns a single character (this is the cause of the problem you see, namely of the program only writing a single, often strange character; you currently simply add up characters, the values overflow of course since the range of char is limited to typically -128..127)
  2. Changing the above causes, as you note in the comments, a follow up problem - how to convert a single character to a string, to which, fortunately, there is an answer already here on SO
  3. Your recursion exit condition - it is n == 1... what about strings of length 1? They will never reach n == 1 ...

To fix problems 2 and 3 at once and simplify your code a little, think about the case of an empty string and whether your code can currently handle that. You can handle that case by simply returning an empty string...

  • Related