{"content":{"id":114,"title":"K\u0026R Solutions - 1.9","body":"\u003cp\u003e\u003cb\u003eQ:\u003c/b\u003e Write a program to copy its input to its output, replacing each string of one or\r\nmore blanks by a single blank.\u003c/p\u003e\r\n\u003cp\u003e\u003cb\u003eA:\u003c/b\u003e\u003c/p\u003e \r\n\u003cpre\u003e\u003ccode class=\"cpp\"\u003e#include \u0026ltstdio.h\u0026gt\r\n\r\nint main(void)\r\n{\r\n int c, blanks;\r\n blanks = 0;\r\n\r\n while ((c = getchar()) != EOF) {\r\n if (c == ' ')\r\n blanks++;\r\n else\r\n blanks = 0;\r\n\r\n if (blanks \u003c 2)\r\n putchar(c);\r\n }\r\n\r\n return 0;\r\n}\r\n\u003c/code\u003e\u003c/pre\u003e\r\n\u003cpre\u003e\u003ccode class=\"cpp\"\u003e\u0026gt ./1.9\r\nhere is a whitespace test\r\nhere is a whitespace test\r\n\u003c/code\u003e\u003c/pre\u003e","publication_date":"2018-06-26T06:00:00.000Z","created_at":"2018-06-19T22:45:59.000Z","updated_at":"2018-06-19T22:58:43.000Z","user_id":1,"rating":null},"tags":"\u003ca class=\"changeable-title\" href=\"/q?tag=k%26r\"\u003ek\u0026amp;r\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=programming\"\u003eprogramming\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=answers\"\u003eanswers\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=c\"\u003ec\u003c/a\u003e"}

K&R Solutions - 1.9

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

A:

#include <stdio.h>

int main(void)
{
  int c, blanks;
  blanks = 0;

  while ((c = getchar()) != EOF) {
    if (c == ' ')
      blanks++;
    else
      blanks = 0;

    if (blanks < 2)
      putchar(c);
  }

  return 0;
}
> ./1.9
here   is  a whitespace   test
here is a whitespace test