我的目标很简单。向用户询问包含大写/小写字母、数字和标点符号的简单文本文件。然后获取文件,打开它,并扫描上述每个元素,并记录每个元素。最后,为每个输出一个总数(即包含的总大写字母、总小写字母、总数字和总标点符号)。
不幸的是,我的问题并不是那么简单。我对 C 将输入文件传递给 fgetc 之类的函数然后对其进行测试以增加计数器的方式究竟是如何(即概念和语法)感到困惑。我的程序崩溃了,我的想法很少。我想我最初的问题是,为什么它会崩溃?我的代码如下;
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char Character = 0;
int words = 0;
int upper_case = 0;
int lower_case = 0;
int punctuation = 0;
int digits = 0;
int entered_words = 0;
char user_filename[100];
char user_filecontent[100];
printf("Enter the filename of the file containing text and/or digits:\n");
printf("(hit the Enter key when done)\n");
gets(user_filename);
FILE *fp;
fp = fopen (user_filename, "r");
if (fp == NULL)
{
printf("\nError, Unable to open the file for reading\n");
}
while((fp = fgetc(fp)) != EOF)
{
while((Character=fgetc(fp)) != '\n');
{
if (isalnum (Character))
{
if (!entered_words)
{
entered_words = 1;
words++;
}
}
else
{
if (entered_words)
{
entered_words = 0;
}
}
if (isupper(Character))
{
upper_case++;
}
else if (islower(Character))
{
lower_case++;
}
else if (isdigit(Character))
{
digits++;
}
else if (ispunct(Character))
{
punctuation++;
}
}
fclose(fp);
}
printf("Total number of words is %d.\n", words);
printf("Total number of digits are %d.\n", digits);
printf("Total number of uppercase letters is %d.\n", upper_case);
printf("Total number of lowercase letters is %d.\n", lower_case);
printf("Total number of punctuation characters is %d.\n", punctuation);
return 0;
}