Name: Anonymous 2008-06-07 13:57
Hey, I've just started learning C and am going through The C Programming Language, reading it and doing the exercises. Up till now everything had been all right, but Exercise 1-8 has been giving me some trouble. If someone could help me out, that'd be very much appreciated. Here's the exercise and my code:
Exercise 1-8: Write a program to count blanks, tabs, and newlines.
code:
#include <stdio.h>
int main()
{
int nl, t, b = 0;
int c;
while ((c = getchar() != EOF)
{
if (c == ' ')
++b;
if (c == '\n')
++nl;
if (c == '\t')
++t;
}
printf("newlines: %d\ntabs: %d\nblanks: %d\n", nl, t, b);
return 0;
}
Now, the problem is this: whenever I give input, the blanks and tab characters are counted properly, but the number of newlines is always some gastronomically high number.
For example, if I give "blah blah blah(tab)dah(new line)" and then give the EOF, I get this:
newlines: 2423969
tabs: 1
blanks: 2
So yeah, that's it. I feel pretty stupid about it, and I get the feeling there's just some really simple, stupid thing that I fucked up, but for the life of me, I can't figure out what it is. Help, please?
Exercise 1-8: Write a program to count blanks, tabs, and newlines.
code:
#include <stdio.h>
int main()
{
int nl, t, b = 0;
int c;
while ((c = getchar() != EOF)
{
if (c == ' ')
++b;
if (c == '\n')
++nl;
if (c == '\t')
++t;
}
printf("newlines: %d\ntabs: %d\nblanks: %d\n", nl, t, b);
return 0;
}
Now, the problem is this: whenever I give input, the blanks and tab characters are counted properly, but the number of newlines is always some gastronomically high number.
For example, if I give "blah blah blah(tab)dah(new line)" and then give the EOF, I get this:
newlines: 2423969
tabs: 1
blanks: 2
So yeah, that's it. I feel pretty stupid about it, and I get the feeling there's just some really simple, stupid thing that I fucked up, but for the life of me, I can't figure out what it is. Help, please?