Complete the program to read in a file and count the number of time each letter
ID: 3749225 • Letter: C
Question
Complete the program to read in a file and count the number of time each letter occurs “a” – “z”, count both “A” and “a” as “a”, also count the number of blanks spaces, and the number of punctuation marks. Print out the results to the screen. Test your code with the three test files (test1.txt, test2.txt, test3.txt) in the Problem 2 repository directory. Copy the screen output and save it to three files labeled out1.txt, out2.txt, and out3.txt, respectively. PLEASE USE C.
Example output:
test1.txt
a - 13
b – 8
...
Blanks – 35
Punctuation - 12
Explanation / Answer
If you have any doubts, please give me comment...
#include<stdio.h>
int main(){
char file[50];
printf("Enter input filename: ");
scanf("%s", file);
FILE *fp;
fp = fopen(file, "r");
if(fp==NULL){
printf("Unable to open file...");
return 0;
}
printf("Enter output filename: ");
scanf("%s", file);
FILE *fout;
fout = fopen(file, "w");
int occur[28] = {0};
char c;
while(!feof(fp)){
fscanf(fp, "%c", &c);
if(c>='a' && c<='z')
occur[c-'a']++;
else if(c>='A' && c<='Z')
occur[c-'A']++;
else if(c==' ')
occur[26]++;
else if(c=='?' || c=='!' || c==',')
occur[27]++;
}
for(int i=0; i<26; i++){
printf("%c - %d ", (i+'a'), occur[i]);
fprintf(fout, "%c - %d ", (i+'a'), occur[i]);
}
printf("Blanks - %d ", occur[26]);
fprintf(fout, "Blanks - %d ", occur[26]);
printf("Punctuation - %d ", occur[27]);
fprintf(fout, "Punctuation - %d ", occur[27]);
fclose(fp);
fclose(fout);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.