if((a[i]=' ')&&(t>max))
// 错误是这里,你每次把空格赋到数组a, 所以最后打印的是空格而不是单词
应该是a[i]==' '
这个是你粗心造成的,建议以后写判断是否相等时,常量放前面,即写成
if(' ' == a[i])
这样,如果你少了一个=号,编译时就会提示错误。
#include
#include
#include
#define M 100
char* compare(char a[])
{
char p[M]; /*这个数组存放单个单词*/
static char q[M]; /*这个数组存放当前长度最长的单词*/
int len; /*len这行字符长度*/
int i,j,k,max,t;
len=strlen(a);
max=0;
t=0;
j=0;
for(i=0;i{
if(a[i]==' ')
/*当遇到空格的时候且当前单词长度大于前面所有单词长度则转存这个单词到q数组*/
{
if(t>max){
max=t;
memset(q,0,M);
for(k=0;kq[k]=p[k];
q[max]='\0';
}
memset(p,0,M);
t=0;
j=0;
}
else /*将每个单词存入p数组*/
{
p[j]=a[i];
t++;
j++;
}
}
if(t>max){
max=t;
memset(q,0,M);
for(k=0;kq[k]=p[k];
q[max]='\0';
}
return q;
}
int main()
{
char a[M];
char* b;
printf("Please enter a line of characters\n");
gets(a);
b=compare(a);
printf("Which is the longest word in the:%s\n",b);
}
原因自己对比一下把
你一遇到空格就把t,j清0了怎么知道哪个单词最长呢