K&R Exercise 1-9 (C)

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

    Here is how I think of the algorithm of this exercise, in pseudo-code:

    define ch and bl (where bl is initially defined to be 0)
    
    while ch is = to getchar() which is not = to end of file  
    do the following:  
          if ch is = to blank and bl is = 0  
              --> output ch and assign the value 1 to bl  
          else --> if ch is = to blank and bl is = 1  
              --> do nothing  
          else --> output ch and assign the value 0 to bl
    

    Example implementation in C:

    #include 
    #include 
    
    main() {
    
       long ch,bl=0;
    
       while ((ch=getchar()) != EOF)
       {
           if (ch == ' ' && bl == 0)
           {
               putchar(ch);
               bl=1;
           } else if (ch == ' ' && bl == 1) {
               // no-op
           } else {
               putchar(ch);
               bl=0;
           }
       }
    
       return 0;
    }
    

提交回复
热议问题