Reputation: 1216
I have written a C code to count no of characters, words and lines in a file.
The code is as follows.
#include "stdio.h"
#include "conio.h"
#define FILE_NAME "abc.txt"
void main()
{
FILE *fr;
int noc = 0;
int now = 0;
int nol = 0;
char ch;
printf("hello world\n");
getch();
//clrscr();
fr = fopen("..\\abc.txt","r");
if(fr == NULL)
{
printf("\n error \n");
getch();
return;
}
ch = fgetc(fr);
while(ch != EOF)
{
printf("%c", ch);
noc++;
if(ch == ' ');
{
now++;
}
if(ch=='\n')
{
nol++;
now++;
}
ch=fgetc(fr);
}
fclose(fr);
printf("\n noc = %d now = %d nol = %d\n", noc, now, nol);
getch();
}
My file abc.txt is as follows.
Hello my friend.
How are you doing?
I am getting following output:
hello world
Hello my friend.
How are you doing?
noc = 38 now = 40 nol = 2
The code is able to read no of characters and no of lines properly. However, it considers each character as a word. I am not understanding where am I going wrong when counting no of words in the code above.
Detailed explanations would be appreciated.
Thanks in advance.
Upvotes: 1
Views: 1789
Reputation: 641
if(ch == ' '); <------- see this (remove semicolon)
{
now++;
}
Upvotes: 4