K&R Exercise 1-9 (C)

后端 未结 30 1508
北荒
北荒 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:30

    Like many other people, I am studying this book as well and found this question very interesting.

    I have come up with a piece of code that only uses what has been explained before the exercice (as I am not consulting any other resource but just playing with the code).

    There is a while loop to parse the text and one if to compare the current character to the previous one. Are there any edge cases where this code would not work ?

    #include 
    
    main() {
    
        // c    current character
        // pc   previous character
        int c, pc;
    
        while ((c = getchar()) != EOF) {
            // A truthy evaluation implies 1 
            // (learned from chapter 1, exercice 6)
            // Avoid writing a space when 
            //  - the previous character is a space (+1)
            //  AND
            //  - the current character is a space (+1)
            // All the other combinations return an int < 2
            if ((pc == ' ') + (pc == c) < 2) {
                putchar(c);
            }
            // update previous character
            pc = c;
        }
    
    }
    

提交回复
热议问题