我是编码的初学者,所以我可能会在这里和那里犯很多新手错误。我们在学校得到了这个任务,目标是找出最长的单词并将其连同它的字符数一起打印出来。我已经走了这么远,但是从这里到现在,我都很难找到问题所在。程序大部分时间都卡在迭代 49、50、51 和 59 上。我认为这是因为 realloc 为最长的 Word 变量返回 NULL。
有什么想法可以尝试解决这些问题吗?提前谢谢各位!
输入:
abc
abcde
abcdefghij
abcdefghij
abcdefghijklmnopq
abcdefghijklmnopq
abcdefghijklmnop
auf wiedersehen
预期输出:
17 characters in longest word: abcdefghijklmnopq
到目前为止我的代码:
#include <stdio.h>
#include <stdlib.h>
//_________//
FILE* fptr;
int c;
int iteration=0; //Just to keep track
//___________Main____________//
int main()
{
fptr = fopen("C:\\....\\input", "r");
char *s;
char *longestWord;
int i=1, charCount=0;
s = (char*) malloc (sizeof(char));
longestWord = (char*) malloc (sizeof(char));
while((c=fgetc(fptr)) != EOF){
iteration++;
printf("Iteration %d\n",iteration);
if (isalpha(c)!=0 ){
s=realloc(s,i*sizeof(char));
s[i]=c;
i++;
}
else if(c==' ' || c =='\n'){
if(i>charCount){
charCount=i-1;
longestWord=realloc(longestWord,i*sizeof(char));
while(longestWord == NULL){
longestWord=realloc(longestWord,i*sizeof(char));
}
for(int t=0;t<i;t++){
*(longestWord+t)=*(s+t);
}
i=1;
}
else{
printf("*********Checkpoint 3***************\n"); //Checkpoint 3
i=1;
}
}
else{
printf("\n\n********Error, got to the else section of the program********\n\n");
}
}
printf("%d characters in the longest word: %s\n",charCount, longestWord);
free(s);
free(longestWord);
fclose(fptr);
return 0;
} //_____________END OF MAIN____________ //