C语言,库stdio.h,stdlib.h和string.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.
(注意: 是文本文件末尾的新行。)
这个问题要求我计算text.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
我只是删除了它上面的动作,输出也发生了变化。我真的不明白为什么会这样。是不是因为我曾经对文本文件进行过一次fscanf?
如何制作21这是第一个代码程序的单词数量的输出?我在这里做错了什么?
答案 0 :(得分:0)
您错过了rewind
可能
rewind(t);
while (fscanf(t, "%s", &b) != EOF)
wrds++;