I'm working through K&R's The C Programming Language. I'm working through an exercise here that says to "Write a program that copies all of its input to its output, replacing each string of one or more blanks by a single blank."
I believe I have solved it. Somewhat. When first running the program with a.out
, I can type in a number with multiple spaces and will get it returned with just one space. But, when I go to the next line and try again, it will return the numbers with no spaces at all. Also, if I type in a string of letters like "33 33 33
" it will only leave one space for the entire line. It becomes "33 3333
".
I know that I could just Google the answer to the exercise itself but I don't think that that would help me learn why my code is behaving the way it is. Any help would be much appreciated.
main()
{
int c, nl, upper;
nl = 0;
upper = 2;
while( ( c = getchar() ) != EOF )
{
if( c == ' ' )
{
++nl;
if( nl >= upper )
{
--c;
--nl;
}
}
putchar(c);
}
}