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
- Instructions said I have to do it in recursion
- 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}