【发布时间】:2016-11-30 13:40:50
【问题描述】:
我正在做一个课堂作业,我们基本上必须提示用户输入两个文本文件。然后程序应该读取文件,显示它们,并显示单独的文件统计信息。
我一直在编写代码,但似乎碰壁了。我似乎只能显示第二个文本文件的统计信息;此外,该文件中的文本似乎没有显示出来。
确实很困惑,所以任何帮助都将不胜感激。尽管我很努力,但我仍然在这门课上苦苦挣扎。 :(
不管怎样,代码(我敢肯定一团糟):
#include <stdio.h>
int main() {
FILE *fp;
char ch;
int lineCount, wordCount, charCount;
char filename[50], filename2[50];
lineCount = 0;
wordCount = 0;
charCount = 0;
printf("Enter a filename: ");
gets(filename);
fp=fopen(filename, "r");
if(fp==NULL) {
printf("Error!\n");
return 1;
}
while((ch=fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
printf("\n");
printf("Enter a second filename: ");
gets(filename2);
fp=fopen(filename2, "r");
if(fp==NULL) {
printf("Error!\n");
return 1;
}
while((ch=fgetc(fp)) != EOF) {
if ( fp )
{
while ((ch=getc(fp)) != EOF) {
if (ch != ' ' && ch != '\n') { ++charCount; }
if (ch == ' ' || ch == '\n') { ++wordCount; }
if (ch == '\n') { ++lineCount; }
}
if (charCount > 0) {
++lineCount;
++wordCount;
}
}
printf("Lines counted: %d \n", lineCount);
printf("Words counted: %d \n", wordCount);
printf("Characters counted: %d \n", charCount);
getchar();
putchar(ch);
}
fclose(fp);
printf("\n");
return 0;
}
【问题讨论】:
-
fgetc返回int,而不是char。请以一致的方式格式化您的代码。并考虑学习如何使用调试器。