计算单词除了文件中的空格

时间:2014-11-25 06:01:38

标签: c

我正在尝试计算名为file.txt的文件中的单词,但它给了我带有空格的字符。 如何计算单词而不计算空格?

#include<stdio.h>
#include<conio.h>
main()
{

 FILE *f1;
 char c;
 clrscr();

 printf("data output");
 f1 = fopen("file.txt","r");
 while((c=getc(f1))!=EOF)
 {
   printf("%c",c);
 }
 fclose(f1);
 getch();
}

请尽快帮我解决。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

// Create a char array to store a word
char word[100];
// Stop when fscanf returns 0
while(fscanf(f1, "%s", word)==1)
{
    // print the word
    printf("%s ",word);
    // Increment count
    count ++;
}
// Print count
printf("%d\n", count );

请记住,假设fscanf没有检查缓冲区溢出,所以没有字长于100个字符