I have written a simple program that counts the number of words in the input stream. There is a small bug in the code and i am not able to figure out the cause of this bug.
#include <stdio.h>
int main()
{
int ichar = 0;
int in_word = 1;
// in_word = 1 *outside a word* in_word = 0 *inside a word*
int wc = 0;
while((ichar = getchar()) != EOF )
{
if ((( ichar != ' ' )||(ichar != '\n' )||(ichar !='\t')) && ( in_word == 1 ))
{
in_word = 0;
wc ++ ;
}
else if (( ichar == ' ' )||(ichar == '\n' )||(ichar =='\t'))
{
in_word = 1;
}
}
printf ( "Total number of words %d\n" , wc);
return 0;
}
an \n
Whenever i give the above input to the program, (the input contains 2 alphabets a,n then followed by a space and enterkey) the output I get
Total number of words 2
Can someone help me understand why i am getting the output as 2 words?
Your code is basically counting characters and not words; try this, I've not tested it, but should work
#include <stdio.h>
int main()
{
int ichar = 0;
int in_word = 1;
// in_word = 0 *outside a word* in_word = 1 *inside a word*
int wc = 0;
while((ichar = getchar()) != EOF )
{
if (( ichar != ' ' )||(ichar != '\n' )||(ichar !='\t'))
{
in_word = 1;
}
else if ((( ichar == ' ' )||(ichar == '\n' )||(ichar =='\t')) && ( in_word == 1 ))
{
in_word = 0;
wc ++ ;
}
}
printf ( "Total number of words %d\n" , wc);
return 0;
}
Every time a letter is in a word and is not whitespace, you add 1 to wc. That happens twice when you type in ab.
I'd use a few loops:
#include <stdio.h>
#include <ctype.h>
int main()
{
int wordcount=0;
while(!feof(stdin))
{
int c;
while(isspace(c=fgetc(stdin));
if(c < 0) break;
wordcount++;
while(!isspace(c=fgetc(stdin)))
{
if(c<0) break;
}
if(c<0) break;
}
printf("wordcount %d\n", wc);
}
if (( ichar != ' ' ) && ( ichar != '\n' ) && ( ichar != '\t' ) && ( in_word == 1 ))
This looks right to me. I'm curious if this was successful?