字符串逆序 如abcdefghijklm后为abcdefmlkjihg 这个错哪里了

#include
using namespace std;
int main(){
char str[50],*p,*q,x;
int n=0,t,i,j;
cout<<"Input a string:";
cin>>str;
p=str;
while(*p!='\0'){
p++;
n++;
}
t=n/2+1;
for(i=t,j=n;i<j;i++,j--){
x=p[i];
p[i]=p[j];
p[j]=x;
}

cout<<"The new string:"<<str;
return 0;

}

while后面的p指向字符串尾

#include<iostream>
using namespace std;

int main() {
    char str[50],*p,*q,x;
    int n=0,t,i,j;
    cout<<"Input a string:";
    cin>>str;
    p=str;
    while(*p!='\0') {
        p++;
        n++;
    }
    t=n/2;
    p=str;
    for(i=t,j=n-1; i<j; i++,j--) {
        x=p[i];
        p[i]=p[j];
        p[j]=x;
    }
    cout<<"The new string:"<<str;
    return 0;

}

int main()
{
    char str[50],*p,x;
    int n=0,i,j;
    cout<<"Input a string:";
    cin>>str;
    p=str;
    while(*p!='\0'){
        p++;
        n++;
    }
    for(i=0,j=n-1;i<j;i++,j--){
        x=str[i];
        str[i]=str[j];
        str[j]=x;
    }

    cout<<"The new string:"<<str;
}

img


测试了一下,代码是原样输出的,这一块代码实现并没有成功进行交换,考虑检查一下这一部分的实现:

img

希望对题主有所帮助!可以的话,帮忙点个采纳!