- #1
Gagan A
- 20
- 0
I did it the following way. The number of characters and lines are coming out fine, but the words are usually more than the actual given by wc.
#include<stdio.h>
int main()
{
FILE *fp;
int words=0,chars=0,lines=0;
char prev,curr; //prev variable is included to exclude multiple spaces.
fp=fopen("input.txt","r");
while((fscanf(fp,"%c",&curr))!=EOF)
{
chars++;
if (curr=='\n') lines++;
if ((curr==' ' && prev!=' ') || (curr=='\n' && prev!='\n')) words++; //prev variable comes into play here. if the current char is a space and the previous was also a space then it should not be counted.
prev=curr;
}
printf("%d %d %d\n",chars,lines,words);
return 0;
}
#include<stdio.h>
int main()
{
FILE *fp;
int words=0,chars=0,lines=0;
char prev,curr; //prev variable is included to exclude multiple spaces.
fp=fopen("input.txt","r");
while((fscanf(fp,"%c",&curr))!=EOF)
{
chars++;
if (curr=='\n') lines++;
if ((curr==' ' && prev!=' ') || (curr=='\n' && prev!='\n')) words++; //prev variable comes into play here. if the current char is a space and the previous was also a space then it should not be counted.
prev=curr;
}
printf("%d %d %d\n",chars,lines,words);
return 0;
}
Last edited: