This is a C program that copies its input to its output, replacing each string of one or more blanks by a single blank. I don't know what is the best way to proceed when the program starts and there isn't a previous value yet.
I have come up with the following:
#include <stdio.h>
void main() {
int actual, previous = -1;
while((actual = getchar()) != EOF) {
if(!(previous == ' ' && actual == ' ')) {
putchar(actual);
previous = actual;
}
}
}
This works, however I was taught that you should not initialize a variable to a random value. Another option would be to use a do-while loop, but then if the program gets an empty file it will go through the if statement for nothing.
I would just set a boolean flag that can be checked and if we're not on the first iteration and the actual and previous character are both spaces we can skip printing the character and updating the previous char and setting the
first_char
flag tofalse
.This way
previous
is never used before being initialized.