文档介绍:实验七指针
目的要求
掌握指针的定义和使用指针变量;
学会使用字符串的指针和指向数组的指针变量;
学会使用指向函数的指针变量;
按实验内容要求完成全程程序设计后才允许上机。
实验内容与步骤
设计一个函数,它有三个形参
被查找的字符串str;
待查找的字符xCh;
在字符串str中xCh出现的位置i=0,1,…
它的返回值是在str中xCh 出现的次数(若str中无xCh,则返回值=0)
上机要求
键入待查的字符xCh;
键入被查的字符串str;
调用该函数;
打印它的返回值和出现的位置;
允许重复执行,每次以清屏开始(用循环语句控制重复执行)。
提示
xCh在str出现位置应设计为一整型指针,以便记下0~N个位置(整数)。
#include<>
void main()
{
char temp;
int run(),j;
int (*prun)();
temp='Y';
while(temp!='N'||temp!='n')
{
if(temp=='Y'||temp=='y')
{
prun=run;
j=(*prun)();
if (j==0)
{
printf("Can Not Find The xCh! j=%d",j);
}
else
{
printf("\nj=%d",j);
}
printf("\nParden>Y/N:");
fflush(stdin);
temp=getch();
}
if(temp=='N'||temp=='n')
break;
if(temp!='Y'&&temp!='y')
{
printf("Wrong!You can only put Y(N) or y(n)\nPlease put again(Y/N):");
fflush(stdin);
temp=getch();
}
}
}
int run (char xCh,char str[100],int i)
{
int j;
char *p;
clrscr();
printf("xCh=");
xCh=getch();
printf("%c\nstr=",xCh);
gets(str);
p=&str[0];
i=0;
j=0;
while(*p)
{
if (*p==xCh)
{
j++;
printf("xCh :%d\t",i);
}
p=p+1;
i++;
}
return j;
}
Mian()版:
#include<>
void main()
{
int i,j;
char xCh,str[100],*p,temp;
temp='Y';/*给temp赋初值Y,防止第一个while循环无法运行*/
while(temp!='N'||temp!='n')/*如果temp不等于n或N时,进行循环*/
{
if(temp=='Y'||temp=='y')/*当temp为y或Y时,进行下列循环,用于进行题目要求的操作*/
{
clrscr();/*清屏*/