m0_63507879 2022-03-18 20:34 采纳率: 81.3%
浏览 29
已结题

字符串逆序 如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;

}

  • 写回答

3条回答 默认 最新

  • fuill 2022-03-18 20:54
    关注

    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;
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 3月27日
  • 已采纳回答 3月19日
  • 创建了问题 3月18日