主函数只运行了一行,到我的第一个函数就结束了,这是怎么回事呢,求解
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define max 3000
struct Dictionary{
int row;
int loc;
int times;
double fre;
char word[30];
};
typedef struct Dictionary dictionary;
void input_words(dictionary allwords[],FILE *fp1)
{
char ch[max], temp;
int line = 1;
int cur_loc = 0;
int num = 0;//单词出现的位置
for (int i = 0; (temp = getc(fp1)) != EOF; i++)//读取文件的所有内容
{
if ((temp >= 65) && (temp <= 90)) //大写转小写
temp = temp + 32;
ch[i] = (char)temp;
ch[i + 1] = '\0';
}
int k = 0;
for(int j = 0;ch[j]!='\0';j++)
{
for(int i = cur_loc;ch[i]!=' '&&ch[i]!=','&&ch[i]!='.'&&ch[i]!='\n';i++)//读取单个单词
{
allwords[j].word[k] = ch[i];
k++;
cur_loc++;
}
k = 0;
cur_loc++;
num++;
allwords[j].row = line;
allwords[j].loc = num;
if(ch[cur_loc] == '\n')
line++;
cur_loc++;
}
printf("1");
}
void compare(dictionary allwords[])
{
for(int i = 0;allwords[i].word != NULL;i++)
{
allwords[i].times = 1;
for(int j = i+1;allwords[j].word != NULL;j++)
{
if(strcmp(allwords[i].word,allwords[j].word) == 0)
{
allwords[i].times++;
memset(allwords[j].word,'0',sizeof(allwords[j].word));
}
}
}
printf("2");
return;
}
void sort(dictionary allwords[],FILE *fp2)
{
dictionary temp[1];
int total = 0;
int n = 0;
for(int i = 0;allwords[i].word != NULL;i++)
{
n++;
if(allwords[i].word != 0)
total++;
}
printf("%d",total);
for(int j = 0;j < n;j++)
{
for(int k = 0;k < (n-j);k++)
{
if(strcmp(allwords[k].word,allwords[k+1].word) > 0)
{
temp[0] = allwords[k];
allwords[k] = allwords[k+1];
allwords[k+1] = temp[0];
}
}
}
for(int m = 0;allwords[m].word != NULL;m++)
{
allwords[m].fre = allwords[m].times/total;
}
fprintf(fp2,"单词总数为:%d\n",total);
}
void output(dictionary allwords[],FILE *fp2)
{
for(int i = 0;allwords[i].word != NULL;i++)
{
if(allwords[i].word[0] != '0')
{
for(int j = 0;allwords[i].word[j] != '\0';j++)
{
fprintf(fp2,"%c",allwords[i].word[j]);
}
fprintf(fp2," 出现次数:%d, 频度:%f, 首次出现在第 %d 行, 第 %d 个\n",allwords[i].times,allwords[i].fre,allwords[i].row,allwords[i].loc);
}
}
printf("3");
return;
}
int main()
{
printf("1");
dictionary allwords[1000];
FILE *fp1;
if ((fp1 = fopen("text.txt", "r")) == NULL)
{
printf("打开文件失败!\n");
exit(EXIT_FAILURE);
}
input_words(allwords,fp1);
printf("2");
fclose(fp1);
compare(allwords);
FILE *fp2 = fopen("结果.txt","a");
sort(allwords,fp2);
output(allwords,fp2);
fclose(fp2);
return 0;
}
不知道你说的到第一个函数就结束是运行完结束还是没运行到就结束.
但这个是用来退出程序的
exit(EXIT_FAILURE);
应该是这里死循环了temp = getc(fp1)) != EOF
EOF改成'\n'试试