A few weeks ago at the recommendation of people I trust, I bought and started reading Kernighan and Ritchie's (K&R) C Programming Language. For one thing, it's damn thin compared to the O'Reilly Practical C I just finished last month. It covers generally the same stuff but in a much more efficient manner. Of course, what do I know? I'm only on chapter 1 and I'm taking K&R's advice and pausing my reading to work through the programming problems in the chapter. One thing that's kind of frustrating to me is that I ran into a problem that seems like it could have an elegant solution, but I've not come up with one. Problem 1-9 which says:
"Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank".
At first I tried coming up with my own code from scratch and wound up with some freakish binary that spit out unprintable characters (probably a mix up in data types). So I started over and entered their file copying program example (1.5.1) from page 16. Then I thought about how to modify it. Here is what I came up with:
#include <stdio.h>
int main()
{
int c, space;
space = 0;
c = getchar();
while (c != EOF) {
if (c == 32 && space == 1)
/* do nothing */;
else if (c != ' ') {
space = 0;
putchar(c);}
else if (c == ' ') {
space = 1;
putchar(c);}
c = getchar();
}
}
(NOTE: I used 32 for space in the first if conditional while testing and didn't switch it back to c == ' '.)
The compiled program works on the most basic level, but I'm sure it's bug ridden and the wrong input will make it barf. Since it does what it's supposed to, I've moved on. But I'm strangely bothered since I *KNOW* there has to be a better way than a bunch of serial if conditionals. I get this nagging feeling that I could do it shorter and with fewer checks.
But I just couldn't do it. Anyone else see where I'm totally off? This is definitely beginner style code and I admit as much. But I was pretty bad in the beginning with Bash too (I had a full page script in 2001 to generate MP3 playlists by traversing directories. Today I have a two liner using the 'find' command), so I think there is hope for my dream of one day being fluent at C. Anyone have any suggestions about my above code? Where could my thinking be improved?
I'll also say that I have a lot of trouble thinking in parallel, but it seems that that is how the best coders think. My code has always been serial in DOS BAT files, CMD, Bash, Perl and now C. Any tips on changing that way of seeing things? Also, let me know if this isn't the right place to post this.
NOTE: I know there's an "answer book" for this book. But I want to do it the "hard way" first and then when I'm done I'll compare my answers with the ones in the answer book.