C++ reverse with for | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C++ reverse with for

Hey in one of the exercises I can't seem to find my mistake. (I know there is a reverse function but id like to understand why I can't fill strings like this #include <iostream> #include <string> using namespace std; bool isPalindrome(int x) { //complete the function string a=to_string(x); string b; for(long int i=a.length();i>=a.length()-1;i--){ b[a.length()-i]=a[i]; } if(b==a){return true;} else{return false;} } int main() { int n; cin >>n; if(isPalindrome(n)) { cout <<n<<" is a palindrome"; } else { cout << n<<" is NOT a palindrome"; } return 0; }

1st Aug 2022, 8:35 PM
Manuel
1 Answer
+ 1
string a = to_string(x); string b; for(long int i=a.length();i!=0;i--){ b.push_back(a[i-1]); }
2nd Aug 2022, 4:33 AM
Raul Ramirez
Raul Ramirez - avatar