Originally Posted by
Subsonics
I think your problem is here:
Code:
b == ' '; /* control for space-as-first-character at the begining of input */
You are not assigning space to b you are comparing it. Should be a single = only.
That did the trick! Thanks! Now to make some sense of this, a single equal sign (=) means that I make the left-hand side take the value of the right hand side (or assign the right-hand side value to the left-hand-side variable), while a double-equal sign (==) asks if the left hand side is equivalent to the right-hand side.
Originally Posted by
Adak
In your loop, you have logic to keep one space inside the string of char's. You don't have the logic in there to handle any leading spaces, in any different way.
Work it through by hand and see what you come up with.
Thanks to you as well! After I fixed the initial condition (b = 0) instead of (b == 0), I noticed that I only had logic to handle the leading spaces for the first string after the program executed. I fixed it by resetting b to 'space' after each newline character. It works now.
Here's the updated code.
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 beginning 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 stepping forward */
if (c == '\n') /* end-of-line check: reset to b = ' ' to handle leading spaces*/
{
b = ' ';
}
}
return 0;
}
Also, I find the code hard to read (as in ugly). Not sure if it's the braces or the misaligned comments. Do you have any suggestions I should pick up before I develop really bad habits?