K&R Exercise 1-9 (C)

后端 未结 30 1457
北荒
北荒 2021-01-31 19:46

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

I\'m assuming by thi

30条回答
  •  轮回少年
    2021-01-31 20:17

    Since relational operators in C produce integer values 1 or 0 (as explained earlier in the book), the logical expression "current character non-blank or previous character non-blank" can be simulated with integer arithmetic resulting in a shorter (if somewhat cryptic) code:

    int c, p = EOF;
    while ((c = getchar()) != EOF) {
        if ((c != ' ') + (p != ' ') > 0) putchar(c);
        p = c;
    }
    

    Variable p is initialized with EOF so that it has a valid non-blank value during the very first comparison.

提交回复
热议问题