I've been working through some books on C trying to get my C legs (sea-legs! Get it?!). I've just finished exercise 1-9 from the K&R book, which for reference is to "write a program to copy its input to its output, replacing each string of one or more blanks by a single blank." I have a question about what's going on with my code, though--
#include <stdio.h>
//Copy input to output. Replace each string of multiple spaces with one single space
int main(int argc, char *argv[]){
int ch, lch; // Variables to hold the current and last characters, respectively
/* This loop should 'put' the current char, then store the current char in lc,
* loop back, 'get' a new char and check if current and previous chars are both spaces.
* If both are spaces, do nothing. Otherwise, 'put' the current char
*/
for(ch = getchar(); (ch = getchar()) != EOF; lch = ch){
if(ch == ' ' && lch == ' ')
;
else putchar(ch);
}
return 0;
}
This mostly works, except for the very first character input. For instance, if the first line input is
"This is a test"
my code outputs
"his is a test".
After dropping the very first character input, the program works consistently to meet the exercise's demands.
Can someone give me an idea of the mistake I made in my loop that's causing the issue? Any other advice is welcome as well.