+ 1
for the code below everything is working but not displaying the output
#include <iostream> #include<string> using namespace std; int main() { string a,b; int n,i,j; cout<<"enter the string to be reversed\n"; cin>>a; cout<<"entered string is\n"; cout<<a<<endl; n=sizeof(a); cout<<"size is: "<<n<<endl; for(i=0;i<=n;i++) { j=n-i; cout<<" j is: "<<j<<endl; b[j]=a[i]; } cout<<"the reversed string is\n"; cout<<b; return 0; }
1 ответ
+ 1
You need to use length() or size() to get the length of a string. And you have to make sure that the range of j is between 0 and a.length()-1. Also, you need to initialize b before starting to use it.
#include <iostream>
#include<string>
using namespace std;
int main() {
string a,b;
int n,i,j;
cout<<"enter the string to be reversed\n";
cin>>a;
b=a;
cout<<"entered string is\n";
cout<<a<<endl;
n=a.length();
cout<<"size is: "<<n<<endl;
for(i=0;i<n;i++){
j=n-i-1;
cout<<" j is: "<<j<<endl;
b[j]=a[i];
}
cout<<"the reversed string is\n";
cout<<b;
return 0;
}