C language, libraries stdio.h, stdlib.h and string.h
Text file (text.txt) contents:
The price of sugar will be increased by RM 0.20 per kg soon. Please consume less sugar for a healthy lifestyle.
(Note: There is a new line at the end of the text file.)
The question asks me to calculate the number of characters, letters, vowels, consonants, spaces and words in text.txt.
Here's my code so far:
FILE *t;
t = fopen("text.txt", "r");
int chrc = 0, ltrs = 0, vwls = 0, cnsnts = 0, blnks = 0, wrds = 0;
char a[1], b[50];
while (fscanf(t, "%c", &a[0]) != EOF) {
chrc++;
if (a[0] >= 65 && a[0] <= 90 || a[0] >= 97 && a[0] <= 122)
ltrs++;
if (a[0] == 'A' || a[0] == 'a' || a[0] == 'E' || a[0] == 'e' || a[0] == 'I' || a[0] == 'i' || a[0] == 'O' || a[0] == 'o' || a[0] == 'U' || a[0] == 'u')
vwls++;
cnsnts = ltrs - vwls;
if (a[0] == 32)
blnks++;
}
while (fscanf(t, "%s", &b) != EOF)
wrds++;
printf("Total number of characters: %d\n", chrc);
printf("Number of letters: %d\n", ltrs);
printf("Number of vowels: %d\n", vwls);
printf("Number of consonants: %d\n", cnsnts);
printf("Number of blanks (spaces): %d\n", blnks);
printf("Approx no. of words: %d\n\n", wrds);
fclose(t);
All of the current output is as expected, except for the number of words. Instead of the expected 21, I get:
Approx no. of words: 0
Then I edited my code to become just this:
FILE *t;
t = fopen("text.txt", "r");
int chrc = 0, ltrs = 0, vwls = 0, cnsnts = 0, blnks = 0, wrds = 0;
char a[1], b[50];
while (fscanf(t, "%s", &b) != EOF)
wrds++;
printf("Approx no. of words: %d\n\n", wrds);
fclose(t);
And I got the expected output:
Approx no. of words: 21
I simply deleted the actions above it and the output changed. I don't really understand why this is. Is it because I had fscanf-ed the text file once before?
How do I make it so 21 is the output for the number of words for the first code's program? What am I doing wrong here?
You missed a rewind
may be
rewind(t);
while (fscanf(t, "%s", &b) != EOF)
wrds++;