No output in word count program in C -


i new learner of c language. got know getchar() function. wrote program count number of words in input. program goes follows: (i using codeblocks):

#include <stdio.h>  main(){ int c, nw;       /*nw stands number of words*/  while((c=getchar())!=eof){     if (c==' '||c=='\t'||c=='\n')         ++nw;  }  printf("number of words are:%d",nw); } 

when run program, takes input, there no output. keeps on taking input no matter how many times press enter.

i tried search million times couldn't find answer.

however, told me include ctrl+d break in while loop. tried same result.

please if has solution me. past 2 weeks trying figure out problem.

thanks!

your loop end when encounters eof(-1).

it keeps on taking input no matter how many times press enter.

because '\n' != eof.

to stimulate eof,

  • press ctrl+z if using windows/dos. must followed enter
  • press ctrl+d if on unix/linux/osx. flushes stdin there characters flushed. otherwise, sends eof stdin.

btw, others have noticed, need initialize nw 0. also, signature of main should int main(void).


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -