K&R Exercise 1.9: Removing spaces at beginning of string
Hello all,
I'm teaching myself C and have begun working through K&R for most of the obvious reasons out there.
On exercise 1.9, about replacing multiple blanks with single blanks, I get my code to work. Continuing in the spirit of the exercise, I tried to remove all spaces at the beginning of the input. So far I've been successful in replacing multiple beginning spaces with a single space, but I can't make that one space go away. If I type a single space at the beginning, it stays there as well.
I checked for answers and found the following two, but neither addresses spaces at the beginning.
http://cboard.cprogramming.com/c-programming/41766-k-r-exercise-1-9-a.html
The C Programming Language Exercise 1-9
Usual beginner restriction applies: can only use what I've learned so far (except for the int main()/return 0 deal, which seems to be a big deal).
Here's my code. What is it doing wrong?
Code:
/* Program to copy its input to its output, replacing each string of one or
more blanks by a single blank. */
#include <stdio.h>
int main()
{
int c, b; /* c = current character, b = previous character */
b == ' '; /* control for space-as-first-character at the begining of input */
while((c = getchar()) != EOF) /* loop sequentially through input until EOF */
{
if (c == ' ') /* space case: check if character is space */
{if (b == ' ') /* b is space: do nothing, step forward the loop */
{
; /* do nothing */
}
}
if (c == ' ') /* space case: check if b is space */
{if (b != ' ') /* b is not space: display character */
putchar(c);
}
if (c != ' ') /* normal case: display the character */
{
putchar(c);
}
b = c; /* Store value of character before steping forward */
}
return 0;
}