I've just started learning C language and as the topic says, I have to write a code that will read another text file and count the number of "characters", "words" and "sentences" until EOF
is reached. My current problems is that I'm not able to produce the right output.
For example a text file containing the following contents...
the world
is a great place.
lovely
and wonderful
should output with 39 characters, 9 words and 4 sentences and somehow I get 50(characters) 1(words) 1(sentences)
This is my code:
#include <stdio.h>
int main()
{
int x;
char pos;
unsigned int long charcount, wordcount, linecount;
charcount = 0;
wordcount = 0;
linecount = 0;
while(pos=getc(stdin) != EOF)
{
if (pos != '\n' && pos != ' ')
{
charcount+=1;
}
if (pos == ' ' || pos == '\n')
{
wordcount +=1;
}
if (pos == '\n')
{
linecount +=1;
}
}
if (charcount>0)
{
wordcount+=1;
linecount+=1;
}
printf( "%lu %lu %lu\n", charcount, wordcount, linecount );
return 0;
}
Thanks for any sort of help or suggestion
char pos; ... while(pos=getc(stdin)
, better to useint pos;
to distinguish the 257 different values returned byfgetc()
- though I doubt this is your current problem, – chux - Reinstate Monica'\n'
is used twice in the if. You are counting words even though it might just be a new row. – Tony Tannousnewline
, you should take that into account. – Weather Vane