改错题
1. 下列给定的程序中,函数proc()的功能是:判断字符ch是否与str所指字符串中的某个字符相同。若相同,则什么也不做;若不同,则将其插在串的最后。
请修改程序中的错误,使它能得出正确的结果。
注意:不要改动main()函数,不得增行或删行,也不得更改程序的结构。
试题程序:
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
//****found****
void proc(char str,char ch)
{
while(*str&&*str!=ch)str++;
//****found****
if(*str==ch)
{str[0]=ch;
//****found****
str[1]='0';
}
}
void main()
{
char str[81],ch;
system("CLS");
printf("\nPlease enter a string:");
gets(str);
printf("\n Please enter the character to search:");
ch=getchar();
proc(str,ch);
printf("\nThe result is%s\n",str);
}
【正确答案】(1)错误:void proc(char str,char ch)
正确:void proc(char*str,char ch)
(2)错误:if(*str==ch)
正确:if(*str=='\0')
(3)错误:str[1]='0';
正确:str[1]='\0';
【答案解析】 形参的个数和类型由调用该函数的实参的个数和类型决定,由main()函数中调用的函数proc()可知,“void proc(char str,char ch)”应改为“void proc(char*str,char ch)”;将字符串中的每一个字符与给定字符比较,当字符串结束或者字符串中有与给定字符相同的字符时结束。如果到字符串的最后一个字符仍没找到与给定字符相同的字符,将给定字符插在字符串的最后,因此,“if(+str==ch)”应改为“if(*str=='\0')”;最后还要为字符串添加一个结束符,因此,“str[1]='0';”应改为“str[1]='\0'”。