In: Computer Science
Adding code that will keep cumulative count of characters?
Hello, I am having issues in figuring out how to keep letter from a .txt file with the declaration of independence, this is my code, I can keep track of the frequency but can't figure out the way to keep adding the total characters, as the you go down the alphabet the number is supposed to be counting up
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
#define DEBUG
void main()
{
FILE* fp;
int numChars[26] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; //26
characters
unsigned char c;
int ndx;
if ((fp = fopen("DOI.txt", "r")) != NULL)
{
while (1)
{
c =
fgetc(fp);
if
(feof(fp))
{
break;
}
if
(!isalpha(c))
{
continue;
}
ndx =
toupper(c) - 'A';
numChars[ndx]++;
}
printf("Letter\tFrequency\tTotal
Characters\n");
printf("------\t---------\t---------------\n");
for (int i = 0; i < 26;
i++)
{
printf("%c\t%3d\t%d\n", i + 'A', numChars[i]); //Here is where I
should add the counter but can't figure out how to make it
work
}
fclose(fp);
}
else
{
perror("Unable to open
file");
}
getchar();
}
//Updated code is in the bold text
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
void main()
{
FILE* fp;
int numChars[26] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; //26
characters
unsigned char c;
int ndx;
if ((fp = fopen("DOI.txt", "r")) != NULL)
{
while (1)
{
c = fgetc(fp);//get the character
if (feof(fp))
{
break;
}
if (!isalpha(c))
{
continue;
}
ndx = toupper(c) - 'A';
numChars[ndx]++;
}
printf("Letter\tFrequency\tTotal Characters\n");
printf("------\t---------\t---------------\n");
int s=0;
for (int i = 0; i < 26; i++)
{
s=s+numChars[i];//take one extra variable add that
to previous value and print that to get cumulative value
printf("%c\t%3d\t\t%d\n",i + 'A',numChars[i],s);
//Here is where I should add the counter but can't figure out how
to make it work
}
fclose(fp);
}
else
{
perror("Unable to open file");
}
}