Tomas Righetti
Tomas Righetti

Reputation: 1

The C Programming Language Exercise 1-9 Problem

i am doing this C exercise and i can't make it work. Any clues as to what am i doing wrong? (I am trying not to use either scanf or printf)

Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

int main()
{
    int currentChar;
    int wasBlank = 0;
    while((currentChar = getchar()) != EOF){
        if (currentChar != ' ') {
            if (wasBlank) {
               putchar(' ');
               putchar(currentChar);
            }
            putchar(currentChar);
        }
        else
            wasBlank = 1;
    }
    return 0;
}

Upvotes: 0

Views: 539

Answers (1)

chux
chux

Reputation: 153338

"wasBlank ... needs to be reset to 0 when you read a non-space char. " is a good first idea, but does not solve the case when the last character before EOF is a single blank.

Print the blank when first seen, not repeated ones.

int main(void) {
  int previousChar = EOF;
  int currentChar;
  while((currentChar = getchar()) != EOF) {
    if (currentChar != ' ' || previousChar != ' ') {
      putchar(currentChar);
    }
    previousChar = currentChar;
  }
  return 0;
}

Upvotes: 1

Related Questions