C语言,库stdio。h、 stdlib。h和字符串。h
问题
文本文件(Text.txt)内容:
The price of sugar will be increased by RM 0.20 per kg soon. Please consume less sugar for a healthy lifestyle.
(注:有
是
文本文件末尾的新行。)
这个问题要求我计算文本中字符、字母、元音、辅音、空格和单词的数量。txt。
以下是我目前的代码:
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);
问题
除字数外,所有电流输出均符合预期。我得到的不是预期的21,而是:
Approx no. of words: 0
然后我编辑了我的代码,变成这样:
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);
我得到了预期的输出:
Approx no. of words: 21
我只是删除了上面的操作,输出就变了。我真的不明白为什么会这样。是因为我以前扫描过文本文件吗?
如何使第一个代码的程序的字数输出为21?我做错了什么?