I'm trying to find out the number of times a letter (say, the letter "b") occurs in paragraph from a file. I'm trying to use arrays to count them, but I'm not sure about how to use the if-else statements properly.
So far all I can do is:
int main(void)
{
FILE *fin = fopen("paragraph.txt", "r");
FILE *fout = fopen("number_of_times_bandc_occurs.txt", "w");
char line[]='\0';
int b=0; int c=0;
while(fscanf("%d", &line) != EOF)
{
//Using the if-else statements here is where I'm having difficulty.
}
fclose(fout);
fclose(fin);
return 0;
}
Btw, I'm kind of a beginner...so I might need some extra explaining. I should also mention that the paragraph has multiple lines of text.
EDIT: I misread you question. To count a specific character you should do something like this:
int ch, countB = 0, countC = 0;
while((ch = fgetc(fp)) != EOF) {
if(ch == 'B')
countB++;
if(ch == 'C')
countC++;
}
Use
int count=0;
while ((ch = fgetc(fp)) != EOF)
{
if (ch == 'b')
{
count++;
}
}
//Then print count
Or
char line[256];
int count=0, i;
char *p;
size_t length;
while(fgets(line, 256, fin))
{
if ((p=strchr(line, '\n')) != NULL)
*p = '\0';
length = strlen(line); //For using strlen() include <string.h>
for(i=0; i < length; i++)
{
if(line[i] == 'b')
count++;
}
}
//Then print count
you can use this simple code patch
long ch_occ[26] = {0};
char ch;
while((ch = fgetc(fp)) != EOF) {
if(ch == 'a')
++ch_occ[0];
else if(ch == 'b')
++ch_occ[1];
else if(ch == 'c')
++ch_occ[2];
.
.
//Similarly you can create for all 26 alphabets;
//then the first index of array ch_occ will have occurrences of 'a' and next index will have of 'b' and so on...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.