Reverse string?

So I recently started learning C++ and stumbled upon this issue.
I don't understand why can I not reverse the string using the following piece of code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include<iostream>
#include<string.h>
using namespace std;
int main(){
    char stri[40], stra[40];
    int a, i, j;
    cout<<"Enter String:- ";
    cin.getline(stri,40);
    a=strlen(stri);
    for(i=0,j=a;i<a;i++,j--){
    stra[i]=stri[j];
    }
    cout.write(stra,40);
    return 0;
}
    


I know there are many other methods to do the same but why won't this method work?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

#include<iostream>
#include<string.h>

using namespace std;

int main(){

    char stri[40], stra[40];
    int a, i, j;

    cout<<"Enter String:- ";
    cin.getline(stri,40);

    a=strlen(stri); 

    for(i=0,j=a-1;i<a;i++,j--){

        stra[i]=stri[j];

    }
    cout.write(stra,a);
    return 0;

}
@Dary Vide

Thanks a lot this worked for me!
As you already know that the index of an array starts from 0, so that, it's range would be [0, length) or [0, length - 1].

If you look at your for loop, one of your index starts from 0 and increasing, while another index starts from *length of the string* and decreasing.
Topic archived. No new replies allowed.