Hello all,
I'm a college guy trying to bone up on my C skills by progressing through the K&R exercises. Here are the two I am concerned with:
1-8: Write a program to count blanks, tabs, and newlines.
My solution...
Code:
#include <stdio.h>
int main(void)
{
int c = 0, blanks = 0, tabs = 0, newlines = 0;
while((c = getchar()) != EOF)
{
switch(c)
{
case ' ':
++blanks;
break;
case '\t':
++tabs;
break;
case '\n':
++newlines;
break;
default:
break;
}
}
printf("\nBlanks: %d\nTabs: %d\nNewlines: %d\n\n", blanks, tabs, newlines);
return 0;
}
1-9: Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
A solution I found online...
Code:
#include <stdio.h>
int main(void)
{
int c;
int inspace;
inspace = 0;
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace == 0)
{
inspace = 1;
putchar(c);
}
}
/* We haven't met 'else' yet, so we have to be a little clumsy */
if(c != ' ')
{
inspace = 0;
putchar(c);
}
}
return 0;
}
My confusion stems from the fact that I can type multiple lines of input before getting an analysis in the first program. However, when I press ENTER for a newline in the second program, the program immediately condenses the line I just typed.
My understanding of the first exercise, or rather my solution to it, is that an initial call to getchar() is made in the while loop, which waits until I hit ENTER, at which point it processes all the stuff I've entered on that particular line with more calls to getchar() because there is more stuff waiting in the text stream. But, nothing is printed because I don't print anything until I break out of the while loop with the EOF signal. Then, it calls getchar() again to wait for more characters and another press of ENTER because I've yet to enter the EOF signal (Ctrl-Z on my setup using Pelles C). First of all, is that a correct assessment of what's going on?
I'm more confused by the solution I encountered to the second exercise, but please tell me if this is correct: Again, I have a while loop that is waiting until I enter the EOF signal, but getchar() is also initially waiting until I hit the ENTER key the first time it is called. When I finally do hit ENTER, the processing of the line I've entered begins. More or less, if I've encountered a space and am already "in space" I simply don't display that extra space, and use the inspace variable to keep track of that condition. Is that all correct?
Mainly, I'm concerned with why I can enter multiple lines before anything happens in the first program and why things immediately happen when I ask for a newline in the second program. I just want to know if the answer I came up with for that is right based on my readings.
Thanks,
-Evan Williams