Below is a small program that I have written to count the number of times a space, newline or tab is entered from the keyboard.
However, I don’t know what’s going wrong. I am getting my counts as zero always no matter how many spaces or newlines are inputted.
#include <stdio.h>
/*program to count blanks ,tabs and newlines */
int main()
{
int cnt_space=0,cnt_newline=0,cnt_tab=0;
int c;
while(c=getchar()!=EOF)
{
if(c==' ')
{
++cnt_space;
}
if(c=='\n')
{
++cnt_newline;
}
if(c=='\t')
{
++cnt_tab;
}
}
printf("spaces=%d\nnewlines=%d",cnt_space,cnt_newline);
return 0;
}
Change this
to
The reason why this matters is that getchar return value gets compared to EOF first, result being 0 or 1. Then the result value gets stored in c. So it would never match any of the conditions.
The reason why getchar gets compared to EOF first is because the != operator has a higher precedence than the = operator.