c语言编程将两个字符串连接起来

#include <stdio.h>
void fun(char p1[], char p2[])
{
int i=0,j=0,n=0;
while(p1[i]!=0)
{
i++;
n++;
}
while(p2[j]!=0)
{
p1[n]=p2[j];
n++;
j++;
}
p2[j]='\0';
}
main()
{char s1[80], s2[40] ;void NONO ();
printf("Enter s1 and s2:\n");
scanf("%s%s", s1, s2);
printf("s1=%s\n", s1);
printf("s2=%s\n", s2);
printf("Invoke fun(s1,s2):\n");
fun(s1, s2);
printf("After invoking:\n");
printf("%s\n", s1);
NONO();
}
void NONO ()
{/* 本函数用于打开文件,输入测试数据,调用fun函数,输出数据,关闭文件。*/
int i ;
FILE *rf, *wf ;
char s1[80], s2[40] ;
rf = fopen("in.dat","r");
wf = fopen("out.dat","w");
for(i = 0 ; i < 10 ; i++) {
fscanf(rf, "%s", s1);
fscanf(rf, "%s", s2);
fun(s1, s2);
fprintf(wf, "%s\n", s1);
}
fclose(rf);
fclose(wf);
}

运行后为何会出现很多“烫烫。。。”啊?

// void fun(char p1[], char p2[]) 的最后一行
p2[j]='\0';
// 改为:
p1[n]='\0';

 

#include <stdio.h>
void fun(char p1[], char p2[])
{
int i=0,j=0,n=0;
while(p1[i]!=0)
{
i++;
n++;
}
while(p2[j]!=0)
{
p1[n]=p2[j];
n++;
j++;
}
p1[n]='\0';
}
main()
{char s1[80], s2[40] ;void NONO ();
     printf("Enter s1 and s2:\n");
     scanf("%s%s", s1, s2);
     printf("s1=%s\n", s1);
     printf("s2=%s\n", s2);
     printf("Invoke fun(s1,s2):\n");
     fun(s1, s2);
     printf("After invoking:\n");
     printf("%s\n", s1);
     //NONO();
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-09-15
void fun(char p1[], char p2[])函数倒数第二行错误
将p2[j]='\0';改为p2[i+j]='\0';

推荐我写的一种将两个字符串连接在一起的函数
#include <assert.h>
void fun(char *p1, char *p2)
{
assert(p1 != NULL); //断言p1不为空
assert(p2 != NULL); //断言p2不为空
while(*p1 != NULL)
p1++;
while((*p1++ = *p2++) != NULL)
;
}
希望对你有所帮助!
第2个回答  2013-09-15
将while(p1[i]!=0)改为while(p1[i]!=’\0‘)
将while(p2[j]!=0)改为while(p2[j]!='\0')
相似回答