Not sure how this simple code works
Hi, I'm not sure how the following code works.
Code:
#include <stdio.h>
/* count lines in input */
int
main()
{
int c, pc; /* c = character, pc = previous character */
/* set pc to a value that wouldn't match any character, in case
this program is ever modified to get rid of multiples of other
characters */
pc = EOF;
while ((c = getchar()) != EOF) {
if (c == ' ')
if (pc != ' ') /* or if (pc != c) */
putchar(c);
/* We haven't met 'else' yet, so we have to be a little clumsy */
if (c != ' ')
putchar(c);
pc = c;
}
return 0;
}
For example if I type in "John _______Smith" and press return I then get "John Smith". The spaces have been removed to just one. I've been looking through this code and disecting it for an hour and I still don't know how it does it. Any simplication of it is appreciated. Below is the original question of the solution........
"Write a program to copy its input to its output, replacing each tab by \t , each backspace by \b , and each backslash by \\ . This makes tabs and backspaces visible in an unambiguous way."