改错题
1. 下列给定的程序中,函数proc()的功能是:将str所指字符串中出现的t1所指字符串全部替换成t2所指字符串,所形成的新的字符串放在w所指的数组中。在此处,要求t1和t2所指字符串的长度相同。
例如,当str所指字符串中的内容为“abcdabcdefg”,t1所指字符串中的内容为“bc”,t2所指字符串中的内容为11时,结果w所指的数组中的内容应为“a11da11defg”。
请修改程序中的错误,使它能得出正确的结果。
注意:不要改动main()函数,不得增行或删行,也不得更改程序的结构。
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
#include <string.h>
//****found****
int proc(char *str, char *t1, char *t2, char*w)
{
char *p, *r, *a;
strcpy(w, str);
while(*w)
{
P=w; r=t1;
//****found****
while(r)
if(*r==*p){r++;p++;}
else break;
if(*r=='<0')
{
=w; r=t2;
//****found****
while(*r){*a=*r;a++;r++}
w+=strlen(t2);
}
else w++;
}
}
void main()
{
char str[100], t1[100], t2[100], w[100];
system("CLS");
printf("<nPlease enter string str:");
scanf("%s",str);
printf("<nPlease enter substring t1:");
scanf("%s",t1);
printf("<nPlease enter substring t2:");
scanf("%s",t2);
if(strlen(t1)==strlen(t2))
{
proc(str,t1,t2,w);
printf("<nThe result is:%s<n",w);
}
else printf("Error:strlen(t2)<n");
}
【正确答案】(1)错误:int proc(char *str, char *t1, char *t2, char *w)
正确:void proc(char *str, char *t1, char *t2, char*w)
(2)错误:while(r)
正确:while(*r)
(3)错误:r++
正确:r++;
【答案解析】 由主函数中proc()函数的调用以及proc()函数的定义,可知该函数没有返回值,因此把proc()前的“int”改为“void”;由proc()函数可知,变量r指向的是字符串t1的地址,while循环要判断的是字符串t1是否结束,因此,“while(r)”应改为“while(*r)”;C语言中,每一条语句都以分号结束,因此,“r++”后要加上分号。