Wrong Output of a C program without errors
Hi guys i just wronte this small program in C using the Notepad++ and Cygwin. So the code is the following:
#include <stdio.h>
int main()
{
int c, i, countLetters, countWords;
int arr[30]开发者_C百科;
countLetters = countWords = 0;
for(i = 0; i < 30; ++i)
arr[i] = 0;
while(c = getchar() != EOF)
if(c >= '0' && c <= '9')
++arr[c - '0'];
else if (c == ' ' || c == '\n' || c == '\t')
++countWords;
else
++countLetters;
printf("countWords = %d, countLetters = %d\n",
countWords, countLetters );
}
but instead of counting words the program counts words as letters and print them as letters and words = 0... where am i wrong because even my teacher couldn`t give me an answer...
Try using curly brackets and the c = getchar()
needs parentheses.
while((c = getchar()) != EOF) {
^ ^
/* Stuff. */
}
The error is here:
while(c = getchar() != EOF)
You need to enclose the assignment in parentheses, like so:
while( (c = getchar()) != EOF) /*** assign char to c and test if it's EOF **/
Otherwise, it is interpreted as:
while(c = (getchar() != EOF)) /** WRONG! ***/
i.e. c is 1 for each char read until the end of file.
The solution:
change while(c = getchar() != EOF), to while((c = getchar()) != EOF)
Reason:
!= has higher priority than =
Hence ,
getchar() != EOF
evaluates to be false and thus becoming
while(c=1) ==> while(0).
Hence, the loop gets iterated with c=1 ,what ever your input be. (except EOF).
In this case Your expression is always evaluates to be false.
since,
if(c >= '0' && c <= '9') is if(1>=48 && 1<=57) and it is always false.
Also,
else if (c == ' ' || c == '\n' || c == '\t')
will evaluated to be false.
Hence the else part countLetters++ will be executed for all inputs!
Resulting in the case as you prescribed.
精彩评论