- 论坛徽章:
- 1
|
这是一个翻转字符串的程序,输入字符串后.什么东西也没有!
1: 回答:
你的 pos 的值不对.
在两个 while 中间加上
pos = pos - 1;
变成
- while(source[pos]!='\0')
- {
- pos=pos+1;
- }
- pos = pos - 1;
- while(pos>;=0)
- {
- dest[j]=source[pos];
- j=j+1;
- pos=pos-1;
- }
复制代码
就可以了.
pos 当第一个循环结束时正好是 strlen(source). 而 source[strlen(source)] 是恒等于 0 的, 所以 dest[0] 就变成了 0, 所以就不对,你想要的数据实际上存放在 dest[1] 开始的内存中.
2: 优化:
其实这个程序跟本用不着这么复杂,我把它改了一下:
- #include "ostream.h"
- #include "istream.h"
- #include "cstring.h"
- int main()
- {
- char source[10];
- cout<<"Enter a string for reversed: "<<endl;
- cin>;>;source;
- int len, j, temp;
- len = strlen(source);
- for( j=0; j<len/2; j++ )
- {
- temp = source[j];
- source[j] = source[len-j-1];
- source[len-j-1] = temp
- }
- cout<<"The reversed string is:"<<source<<endl;
- return 0;
- }
复制代码
少用了一个数组,少了一次循环. |
|