我的程序应该在另一个输出文件中打印一个输入文件的字母频率和数字总和。字母频率工作正常。问题在于,总和部分被编译器忽略,因此它输出字母频率,总和为0。
我已经尝试了一些方法,但是我不知道问题出在哪里。希望你能帮助:)
所以这是代码:
#define MAX_FILE_NAME 100
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void text_analysis(FILE*,FILE*, int,int freq [] );
int main()
{
FILE *in, *out;
int frequency[26] = {};
char filename[MAX_FILE_NAME];
int a, sum = 0;
int ch = 0;
//Give the name of the file you want to open
printf("Enter file name: ");
scanf("%s", filename);
// Open the file in to read
in = fopen(filename, "r");
if (in == NULL)
{
printf("Could not open file %s",
filename);
return 0;
}
//Open the file out to write the output
out = fopen("output.txt", "w");
if (out == NULL)
{
printf("Cannot open destination file.\n");
exit(1);
}
do {
// read each character from input file
ch = fgetc(in);
//read all the numbers in the file and calculate the sum
if( isdigit( (char)ch ) )
{
ungetc( (char)ch, in );
if( fscanf( in, "%8d", &a ) != 1 )
{
fprintf( stderr, "fscanf for number failed\n" );
}
sum += a;
}
//Call the function to analyse the text and return the frequency of the letters in the file
text_analysis(in,out, ch, frequency);
}
while (!feof(in));
//Print the sum of the numbers in the file
fprintf(out, "\n The sum of all numbers in the file is: %d \n", sum);
//Close the files
fclose(out);
fclose(in);
return 0;
}
void text_analysis(FILE *in,FILE *out, int c, int freq[]) {
while ( (c = fgetc(in)) != EOF)
{
/** Considering characters from 'a' to 'z' only
and ignoring others */
if ('a' <= c && c <= 'z')
freq[c-'a']++;
else if('A' <= c && c <= 'Z')
freq[c-'A']++;
}
//Print the letters a-z and the frequency in the output file
fputs("character\t\t\t\tfrequency", out);
for (c = 0; c < 26; c++)
{
fprintf(out, "\n%c\t\t\t\t\t\t%2d", c+'a',freq[c]);
}
}
最佳答案
您没有提供示例输入,所以我只是在猜测:
您的输入以非数字字符开头。
然后,您的do
-while()
循环在主调用text_analysis()
中,该循环通过其while
循环读取整个输入。
返回后,main
的循环结束,您的sum
为0。