连接连个字符串后,输出有乱码,求助
/* 编一程序,将两个字符串连接起来,不要用strcat函数。 */
#include <iostream>
#include <string>
using namespace std;
void scat(char *,char *);
void main()
{
string a,b;
cout<<"enter:"<<endl;
getline(cin,a);
getline(cin,b);
scat(&a[0],&b[0]);
cout<<a<<endl;
}
void scat(char *p,char *q)
{
while(*p != '\0')
{
p++;
}
while(*q != '\0')
{
*p = *q;
p++;
q++;
}
}
[解决办法]
//确保p有足够的空间
void scat(char* p,char const* q)
{
while(*p)
{
p++;
}
while(*q)
{
*p = *q;
p++;
q++;
}
//加上这句
*p = 0;
}
int main()
{
char a[32];
a[0] = 0;
scat(a, "hello");
scat(a, " world");
return 0;
}