看看下面程序有什么错误,怎么修改啊

来源:百度知道 编辑:UC知道 时间:2024/05/22 12:58:46
#include"iostream.h"
int find(char s[],char t[]);
const int MAXLINE =256;
int main()
{
char source[MAXLINE],target[MAXLINE];
cout <<"Please input a string for searching:\n";
cin.getline(source,MAXLINE);
cout<<"Please input a string you want to find:\n";
cin.getline(target,MAXLINE);
int intpos =find(source,target);
if(intpos>=0)
cout<<"Finding it.The target string is at index"<<intpos<<"OF string\n?";
else
cout<<"Not finding it.\n";
return 0;
}
int find(char a[],char b[])
{
int t;
for(int i=0;;i++)
{
for(int j=0;;j++)
if(a[i+j]==b[j])
t=i;
else t=-1;

}
return t;
}
目的是在数组a中查找数组b,找到返回位置,没找到返回-1
高手们请帮帮我吧, 必有重谢啊!

find()函数出了问题:
for(int j=0;;j++)
if(a[i+j]==b[j])
t=i;
else t=-1;
这个for语句没有停止条件,会超越数组的边界,故不能正确运行。
下面这个可以运行:
int find(char a[],char b[])
{
int t,bn,an;
an=strlen(a);
bn=strlen(b);
for(int i=0;i<an;i++)
{
for(int j=0;j<bn;j++)
{
if(j==0) t=i+j;
if(a[i+j]!=b[j]) break;
if(j==bn-1) return t;
}
}
return -1;
}