免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2549 | 回复: 3
打印 上一主题 下一主题

这是一个翻转字符串的程序,输入字符串后.什么东西也没有! [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2003-01-17 14:18 |只看该作者 |倒序浏览

  1. #include "ostream.h"
  2. #include "istream.h"
  3. #include "cstring.h"
  4. int main()
  5. {
  6.         char source[10],dest[10];
  7.         cout<<"Enter a string for reversed: "<<endl;
  8.         cin>;>;source;
  9.         int pos=0,j=0;
  10.         while(source[pos]!='\0')
  11.         {
  12.                 pos=pos+1;
  13.         }
  14.         while(pos>;=0)
  15.         {
  16.                 dest[j]=source[pos];
  17.                 j=j+1;
  18.                 pos=pos-1;
  19.         }
  20.        
  21.         int temp;
  22.         temp=strlen(source);
  23.         cout<<temp<<endl;
  24.         dest[temp+1]='\0';
  25.         cout<<"The reversed string is:"<<dest<<endl;
  26.         return 0;

  27. }
复制代码


请帮忙看一下,多谢!

论坛徽章:
0
2 [报告]
发表于 2003-01-17 14:48 |只看该作者

这是一个翻转字符串的程序,输入字符串后.什么东西也没有!

什么都没做当然什么都没有了,建议好好看看吧!

论坛徽章:
1
2015年辞旧岁徽章
日期:2015-03-03 16:54:15
3 [报告]
发表于 2003-01-17 15:58 |只看该作者

这是一个翻转字符串的程序,输入字符串后.什么东西也没有!

1: 回答:
你的 pos 的值不对.
在两个 while 中间加上
pos = pos - 1;
变成
  1.   while(source[pos]!='\0')
  2.    {
  3.       pos=pos+1;
  4.    }
  5.    pos = pos - 1;
  6.    while(pos>;=0)
  7.    {
  8.       dest[j]=source[pos];
  9.       j=j+1;
  10.       pos=pos-1;
  11.    }
复制代码

就可以了.
pos 当第一个循环结束时正好是 strlen(source). 而 source[strlen(source)] 是恒等于 0 的, 所以 dest[0] 就变成了 0, 所以就不对,你想要的数据实际上存放在 dest[1] 开始的内存中.
2: 优化:
其实这个程序跟本用不着这么复杂,我把它改了一下:
  1. #include "ostream.h"
  2. #include "istream.h"
  3. #include "cstring.h"
  4. int main()
  5. {
  6.    char source[10];
  7.    cout<<"Enter a string for reversed: "<<endl;
  8.    cin>;>;source;
  9.    int len, j, temp;
  10.    len = strlen(source);
  11.    for( j=0; j<len/2; j++ )
  12.    {
  13.        temp = source[j];
  14.        source[j] = source[len-j-1];
  15.        source[len-j-1] = temp
  16.    }

  17.    cout<<"The reversed string is:"<<source<<endl;
  18.    return 0;
  19. }
复制代码

少用了一个数组,少了一次循环.

论坛徽章:
0
4 [报告]
发表于 2003-01-17 16:09 |只看该作者

这是一个翻转字符串的程序,输入字符串后.什么东西也没有!

格式如下:
在第一行输入一方括号[],在里面输入code,即[code];代码的最后一行再输入一方括号[],里面加上/code,最后再在这两行之前加入代码即可.
这样就OK了.
这个在你当版主以后也许 会用上的
你要当版主?我支持你.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP