改错题
下列给定程序中,函数proc()的功能是:首先把b所指字符串中的字符按逆序存放,然后将str1所指字符串中的字符和str2所指字符串中的字符,按排列的顺序交叉合并到str所指数组中,过长的剩余字符接在str所指数组的尾部。
例如,当str1所指字符串中的内容为“ABCDEFG”,str2所指字符串中的内容为“1234”时,str所指数组中的内容应该为“A483C2D1EFG”;而当str1所指字符串中的内容为“1234”,str2所指字符串中的内容为“ABCEDFG”时,str所指数组中的内容应该为“1G2F3E4DCBA”。
请修改程序中的错误,使它能得出正确的结果。
注意:不要改动main()函数,不得增行或删行,也不得更改程序的结构。
试题程序:
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
void proc(char *str1,char *str2,char *str)
{
int i,j;char ch;
i=0;j=strlen(str2)-1;
//****found****
while(i>j)
{
ch=str2[i]:str2[i]=str2[j];str2[j]=ch;
i++;j--;
}
while(*str1||*str2)
{
if(*str1){*str=*str1;str++;str1++;}
if(*str2){*str=*str2;str++;str2++;}
}
//****found****
*str=0:
}
void main()
{
char s1[100],s2[100],t[200];
system('CLS');
printf('\nEnter s1 string:');
scanf('%s',s1);
printf('\nEnter s2 string:');
scanf('%s',s2);
proc(s1,s2,t);
printf('\nThe result is:%s\n',t);
}
【正确答案】(1)错误:while(i>j) 正确:while(i<j) (2)错误:*str=0; 正确:*str='\0';
【答案解析】由函数proc()可知,变量i和j分别存放的是字符串str前面和后面第i个字符的位置,当i<j时,两个位置的字符交换。因此,“while(i>j)”应改为“while(i<j)”;交叉合并完成后,要为新的字符串添加结束符,因此,“*str=0;”应改为“*str='\0';”。