K&R Exercise 1-9 (C)

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

    Here is my answer, I am currently in the same spot you were years ago.

    I used only the syntax taught until this point in the books and it reduces the multiple spaces into one space only as required.

    #include
    int main(){
        int c
        int blanks = 0; // spaces counter
        while ((c = getchar()) != EOF) {        
            if (c == ' ') { // if the character is a blank
                while((c = getchar()) == ' ') { //check the next char and count blanks
    
                    blanks++;
    
                    // if(c == EOF){
                    // break;
                    // }
                }            
                if (blanks >= 0) { // comparing to zero to accommodate the single space case, 
                                   // otherwise ut removed the single space between chars
                    putchar(' '); // print single space in all cases                    
                }
    
            }
            putchar(c); //print the next char and repeat        
        }
    
    
        return 0;
    }
    

    I removed the break part as it was not introduced yet in the book,hope this help new comers like me :)

提交回复
热议问题