questions about getchar() and EOF
Ok, I am revisiting the whole getchar() and EOF thing here.
I am still working through K&R, as time permits (I work at a totally unrelated job, so sometimes I do not get a lot of time to learn C) and I got to exercise 1-8, where they want a program that counts blanks, tabs, and newlines. So anyway, I do not have the book with the answers to K&R. I do have some answers online, however they do not help me to understand the why of the whole thing, meaning that I don't really learn why I am doing stuff. It would be like me asking you guys to write the program for me. I think my problem lies with a poor understanding of getchar() and EOF. Of course some of you will likely tell me that my problems lie with a poor understanding of C... :) Anyway, if there are any of you who can help me with understanding what is going on with the question, and why my code does not do what I want it to, I would appreciate it a lot.
Here is what I did (I will list what it does when I run it following...)
Code:
#include <stdio.h>
/* Program to count blanks, tabs, and newlines (Exercise 1-8 in K&R) */
int main(void)
{
int c, nl, tab, blank;
nl = 0;
tab = 0;
blank = 0;
while ( ( c = getchar() ) != EOF )
if ( c == '\n' )
++nl;
printf( "There were %d new lines\n", nl );
if ( c == '\t' )
++tab;
printf( "There were %d tabs\n", tab );
if ( c == ' ' )
++blank;
printf( "There were %d blanks\n", blank );
return 0;
}
Ok, so here is what happens when I run it:
Quote:
[Tue Feb 4 ~/cprograms]$count_tabs
testing my program. a tab here, and some spaces here
and then a new line
and another tab and then another, and another,
newline
There were 8 new lines
There were 0 tabs
There were 0 blanks
It seems to do the newlines thing right, but it better, as it is basically right out of the book. Anyway, enough out of me here, as I don't get it. Hopefully someone will help. Thanks.
kermit