The program is intended to count the number of characters, words and lines entered. the program runs fine if only one line of text is entered, but if more that one line of text is entered the "number of words" that the program outputs is incorrect: here's my code
Code:
#include <stdio.h>
int main(void){
int c;
int cha=0; // character counter
int wd=0; // word counter
int nl=0; // newline counter
int flag=0;
while( (c=getchar() )!= EOF){
if(c=='\n'){
nl++;
}
if (c!='\n'){
cha++;
if(c==' '){
flag=0 ;
}
else if(flag==0){
wd++;
flag=1;
}
}
}
printf("The string entered is %d lines,",nl);
printf("contains %d words,",wd);
printf("and is %ld characters long",cha);
getchar();
return 0;
}
please help me it's frustrating