K&R Exercise 1-9 (C)

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

    To do this using only while loops and if statements, the trick is to add a variable which remembers the previous character.

    Loop, reading one character at a time, until EOF:
        If the current character IS NOT a space:
            Output current character
    
        If the current character IS a space:
            If the previous character WAS NOT a space:
                Output a space
    
        Set previous character to current character
    

    In C code:

    #include 
    
    main()
    {
        int c, p;
    
        p = EOF;
    
        while ((c = getchar()) != EOF) {
            if (c != ' ')
                putchar(c);
    
            if (c == ' ')
                if (p != ' ')
                    putchar(' ');
    
            p = c;
        }
    }
    

提交回复
热议问题