I get an error on this line: rev(s[s.length]);
Sep 22, 2017 at 7:23am UTC
I am trying to compile this program and I get this error:
20 10 C:\Dev-Cpp\MalikChapter6\reverseString.cpp [Error] no match for 'operator[]' (operand types are 'std::string {aka std::basic_string<char>}' and '<unresolved overloaded function type>')
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include<iostream>
#include<cstring>
#include<cctype>
string rev(string s);
using namespace std;
int main() {
string s;
cout<<"\nEnter a string: \n" ;
cin >> s;
cout<<"The string in reverse is: " ;
rev(s) ;
}
string rev(string s) {
if (!s.empty()) {
rev(s[s.length]);
}
cout<< s[0];
}
Sep 22, 2017 at 7:44am UTC
Add the parentheses after length:
rev(s[s.length() ]);
Actually it is out of bounds add -1.
Also rev(...) needs to return a string.
Sep 22, 2017 at 8:24am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14
std::string rev_1( std::string str )
{
const auto sz = str.size() ;
if ( sz < 2 ) return str ;
else return str.back() + rev_1( str.substr( 1, sz-2 ) ) + str.front() ;
}
std::string rev_2( std::string str ) { return { str.rbegin(), str.rend() } ; }
std::string rev_3( std::string str )
{
std::reverse( str.begin(), str.end() ) ;
return str ;
}
Sep 22, 2017 at 9:05am UTC
Thank you all!!!
It worked so well!!!!!!!!!
Topic archived. No new replies allowed.