一个小程序,怎么也看不出哪里错了
编写一个将字符串ABCD逆置的函数(即DCBA),函数原型如下:void reverse(char* s)
下面是我编写的程序,在VC++6.0下编译通过,可出不来结果,请各位大虾不吝赐教,多谢了!
#include <iostream>
using namespace std;
int getlength(char* p)
{
int length = 0;
while(p[length] != '\0')
length++;
return length;
}
void reverse(char* t)
{
int len = getlength(t);
char temp;
for(int i = 0; i < len/2; i++)
{
temp = t[i];
t[i] = t[len-1-i];
t[len-1-i] = temp;
}
}
int main()
{
char* s = "ABCD";
int l = getlength(s);
reverse(s);
for(int i = 0; i < l; i++)
cout << s[i];
return 0;
}
[解决办法]
#include <iostream > using namespace std; int getlength(char* p) { int length = 0; while(p[length] != '\0') length++; return length; } void reverse(char* t) { int len = getlength(t); char temp; for(int i = 0; i < len/2; i++) { temp = t[i]; t[i] = t[len-1-i]; t[len-1-i] = temp; } } int main() { char s[] = "ABCD"; //如果是一个char*的常量字符串,是不能改变它的值的 int l = getlength(s); reverse(s); for(int i = 0; i < l; i++) cout<< s[i]; cout<<endl; return 0; }