我正在尝试建立一个计数器,该计数器将对文本文件中的单词和句子进行计数。我正在努力在程序中实现字母数字查找器。我需要帮助。这是我到目前为止所得到的。该程序计数不正确。它一直在计算空格。
int main (void)
{
// Local Variables
char path[30] ; // File path size
unsigned int words ; //total number of words
unsigned int sentences ; //total number of sentences
char ch ;
FILE *file; // text file to be opened
// Intialize counter variables
words = 0;
sentences = 0;
//prompt user for file path
printf ("enter source file path: ");
//stores the file name in path.
scanf ( "%s" , path);
//reads file name
file = fopen ( path , "r");
//check if file name is valid
if ( file == NULL )
{
printf ( "Please enter a valid file name" );
}
//while function to count sentences and words
while (( ch = fgetc(file)) != EOF )
{
// check for a period, exclamation or question mark.
//if true count sentence
if ( (ch == '.') || (ch == '!') || (ch == '\?') )
{
sentences++;
}
// if there is a space or tab or space is true. count words
else if ( ch == ' ' || ch == '\t' )
{
words++;
}
}
//displays to the user the amount of words and sentences in the text file.
printf ( "total words = %d\n" , words );
printf ( "total sentences = %d\n" , sentences);
}
正如Arkku所述,您可能要防止出现多个空格或多个句点等,从而给您一个错误的计数,该计数过高。
您可以使用其他状态/类型变量来处理。
这里是代码的少许重构(请注意,switch/case
有点干净)。另外,我添加了换行符(\n
)作为单词分隔符,并将'\?'
更改为'?'
:
//while function to count sentences and words
int type = -1;
while ((ch = fgetc(file)) != EOF) {
switch (ch) {
// check for a period, exclamation or question mark.
// if true count sentence
case '.':
case '!':
case '?':
if (type != 1)
sentences++;
type = 1;
break;
// if there is a space or tab or space is true. count words
case ' ':
case '\t':
case '\n':
if (type != 2)
words++;
type = 2;
break;
default:
type = 0;
break;
}
}