-1

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}   
  • Do you need to do it recursively? This just makes the task more complicated if you ask me...anyway on a first glance, the `n == 1` condition looks wrong... – codeling Apr 10 '22 at 14:57
  • Yes, the instructions said I have to do it in recursion. By the way I have changed from n == 1 to 0 but problem still exists – Interference Apr 10 '22 at 14:57
  • 3
    You return a `char` which is a single character. The + operation you are doing sums the ascii value of all characters. – drescherjm Apr 10 '22 at 15:00
  • Yes, but somehow I cannot do it using string. If I declare the function using a string, error pops up. – Interference Apr 10 '22 at 15:00
  • @drescherjm Wait how? I don't get what the compiler says, but I only get the location of the error. – Interference Apr 10 '22 at 15:03
  • Related: [https://stackoverflow.com/questions/4728699/preferred-conversion-from-char-not-char-to-stdstring](https://stackoverflow.com/questions/4728699/preferred-conversion-from-char-not-char-to-stdstring) – drescherjm Apr 10 '22 at 15:03
  • Also: [https://stackoverflow.com/questions/17201590/c-convert-from-1-char-to-string](https://stackoverflow.com/questions/17201590/c-convert-from-1-char-to-string) – drescherjm Apr 10 '22 at 15:07
  • Your function returns a char, but it must return a string. –  Apr 10 '22 at 15:11
  • 2
    You can use [`s.substr(x, 1)`](https://en.cppreference.com/w/cpp/string/basic_string/substr) instead of `s[x]` and return a string. – jabaa Apr 10 '22 at 15:13
  • 1
    @Diffract *I do not know what the problem in the C++ program is, since the Python counterpart works well.* -- Your first mistake is to try and write C++ code using Python as a model. You cannot "translate" from one language to another like that -- you have to know both languages first. Then the next step is to throw the Python version away, and implement the solution using C++ *using the idioms of C++*, not Python-like code. – PaulMcKenzie Apr 10 '22 at 15:37

1 Answers1

1

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...

codeling
  • 11,056
  • 4
  • 42
  • 71
  • Solved. Suggestion 2 is actually the problem I was looking for. I can change return s[0]; into string r(1, s[0]); return r; – Interference Apr 10 '22 at 15:16
  • even better, as I note on below the list, try and think about handling the empty string correctly as well, then you don't even need the char to string conversion! – codeling Apr 10 '22 at 15:17
  • Oh, I actually tried as well, but it popped up funny characters. I did """return s[0] + "";""" for that line. – Interference Apr 10 '22 at 15:20
  • 1
    `if (n < 0) { return string(); }` works perfectly for me without "funny characters" ;) – codeling Apr 10 '22 at 15:22
  • Oh, it worked as well. Can't believe that. I have no idea what string() however. Is it possible to describe this as well please? I'm a beginner. – Interference Apr 10 '22 at 15:25
  • this is simply the default constructor of the string class which creates an empty object. see [cppreference](https://en.cppreference.com/w/cpp/string/basic_string/basic_string) for all available constructors – codeling Apr 10 '22 at 15:27
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/243767/discussion-between-diffract-and-codeling). – Interference Apr 10 '22 at 15:30