I'm trying to reverse a string using an array and string. This is my code. I am facing an issue when I try to print reverse_s
for any string, e.g. "raj". So it is giving me "jar", i.e. the reverse of string, but the main problem is it is giving me some random characters after "jar" just like jar▀≈¶@
.
Please help me finding the problem and debug my code.
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
int lenOfStr = s.length();
cout<<lenOfStr<<endl;
char reverse_s[lenOfStr];
int j=0;
for(int i=(lenOfStr-1); i>=0; i--){
reverse_s[j] = s[i];
j++;
if(j==(lenOfStr)){
break;
}
}
cout<<"Reverse string is "<<reverse_s<<endl;
// sizeof operator can be used to find out the lenght of array in cpp
cout<<"Thelength of my array is "<<sizeof(reverse_s)<<endl;
cout<<reverse_s[5]<<endl;
return 0;
}
I'm new in programming.