这个程序哪里有问题?(C++)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
//using namespace std;
void fun(char str[], char strmax[])
{
int i, k, m, n = 0, f;
char strmax1[20];
for (i = 0; str[i] != '\0'; i++)
{
if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
{
m = 0;
for (k = i; str[k] != '\0' && (str[k] >= 'a' && str[k] <= 'z' || str[k] >= 'A' && str[k] <= 'Z'); k++)
{
strmax1[m] = str[k];
m++;
}
strmax1[m] = '\0';
if (n < m)
{
for (f = 0; f <= m; f++)
strmax[f] = strmax1[f];
n = m;
}
i = k - 1;
}
}
}
int main(void)
{
char strmax[20] = "";
char str[100];
ifstream in("fl.dat");
if(!in)
{cerr<<"open error!"<<endl;
exit(1);
}
for(;in>>str;)
fun(str, strmax);
cout<<"其中最长的单词是:"<<strmax<<endl;
cout<<"其长度为:"<<strlen(strmax)<<endl;
return 0;
}
编译执行都没有问题,但是输出的不是文本中的最长单词及其长度,而是最后一个单词及其长度,怎么回事?
参考答案:/*这主要是因为fun函数被多次调用,而n的值是保存的最长的单词长度,
每次被重复调用fun时,n的值都被清零了,所以会出现每次都是最后一个单词,将n设定为static时,它的值会被保留下来,以后多次调用fun时,n的值都会保存,所以能够得出正确的结果。*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
//using namespace std;
void fun(char str[], char strmax[])
{
int i, k, m, f;
static int n=0;
char strmax1[20];
for (i = 0; str[i] != '\0'; i++)
{
if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
{
m = 0;
for (k = i; str[k] != '\0' && (str[k] >= 'a' && str[k] <= 'z' || str[k] >= 'A' && str[k] <= 'Z'); k++)
{
strmax1[m] = str[k];
m++;
}
strmax1[m] = '\0';
if (n < m)
{
for (f = 0; f <= m; f++)
strmax[f] = strmax1[f];
n = m;
}
i = k - 1;
}
}
}
int main(void)
{
char strmax[20] = "";
char str[100];
ifstream in("fl.dat");
if(!in)
{cerr<<"open error!"<<endl;
exit(1);
}
for(;in>>str;)
fun(str, strmax);
cout<<"其中最长的单词是:"<<strmax<<endl;
cout<<"其长度为:"<<strlen(strmax)<<endl;
return 0;
}