I was working on a white space compacting program, and I came up with this code which seems to work nicely:
However, I was flipping through K&R2 and I saw another way which I tried and it works:Code:#include <stdio.h> /* replace_blanks.c - September 29, 2003 * by Rob Somers * An answer to exercise 1-9 in K&R II * If the character is a space, print it, then * check the next character, and if it is a space, * delete the previous space, and print the new one */ int main(void) { int c; while( ( c = getchar() ) != EOF ) { if( ( c == ' ' ) ){ putchar( c ); while( ( c = getchar() ) == ' ' ){ printf( "\b " ); } } putchar( c ); } return 0; }
Now why does the semi-colon work? (The semi-colon replaces the line in red on the first version) Is the while loop saying in effect, "If this condition, do nothing" ? So that way it prints no space after the initial space? The second version looks to be a better solution, not?Code:#include <stdio.h> /* replace_blanks_2.c - September 29, 2003 * by Rob Somers * An answer to exercise 1-9 in K&R II */ int main(void) { int c; while( ( c = getchar() ) != EOF ) { if( ( c == ' ' ) ){ putchar( c ); while( ( c = getchar() ) == ' ' ){ ; } } putchar( c ); } return 0; }
~/kermit



LinkBack URL
About LinkBacks



