235k views
1 vote
Write a C program to output the number of sentences from a file?

1 Answer

1 vote

Final answer:

The student's question involves writing a C program to count the number of sentences in a file. The program should read through the file and increment a counter when it encounters sentence terminators. The total count is then outputted.

Step-by-step explanation:

The student is asked to write a C program that will read the contents of a file and count the number of sentences within it. In programming, a common approach to determining the end of a sentence is to look for sentence terminators such as periods (.), exclamation points (!), and question marks (?). Here is a simple program in C that accomplishes this task:

#include

int main() {
FILE *file;
char filename[100], character;
int sentences = 0;

printf("Enter the filename to open for reading \\");
scanf("%s", filename);

file = fopen(filename, "r");

if (file == NULL) {
printf("Could not open file %s", filename);
return 1;
}

while ((character = fgetc(file)) != EOF) {
if (character == '.' || character == '?' || character == '!') {
sentences++;
}
}

printf("The file %s contains %d sentences.", filename, sentences);

fclose(file);

return 0;
}

This program prompts the user for a file name, and then reads through the file character by character. It increments a counter every time a sentence terminator is encountered. After reading the entire file, it outputs the total number of sentences found.

User Bojan Jovanovic
by
7.7k points