the c programing language 1-22 较长输入行折成短些的多行,非缓冲方式实现

/*
 * K&R2 1-22
 * Author: Donmmi
 * 程序说明: 
        代码核心部分:折行后的当前行长度为未输出的空白字符数(len = nspace),再根据折行位置进行处理
*/

#include 

#define NLINE   4
#define NTAB    2

int main(void) {
    int     i, c;
    int     len, nspace;

    len = nspace = 0;

    while ((c = getchar()) != EOF) {
        /* 非空格和非换行符 */
        if (c != ' ' && c != '\t') {
            ++len;
            while (nspace) {    /* 遇到非空白字符,首先输出空白符,空格数目保存在nspace中 */
                putchar(' ');
                --nspace;
            }
            putchar(c);
            if (len == NLINE) {
                if (c != '\n')      /* 如果在需要折行的位置字符为换行符,则不输出换行符 */
                    putchar('\n');
                len = 0;
            }
            if (c == '\n')
                len = 0;
        } else {    /* 空格或tab */
            if (c == ' ') {
                ++len;
                ++nspace;
            } else if (c == '\t') {
                len += NTAB;
                nspace += NTAB;
            }

            /* 由于tab的原因,len可能会大于NLINE,处理多余的空白行输出 */
            if (len >= NLINE) { /* 需要折行 */
                if (len > nspace)    /* 如果len>nspace先输出一个换行符 */
                    putchar('\n');
                if (nspace / NLINE > 0)
                    for (i = 1; i <= nspace / NLINE * NLINE; ++i) { /* 输出一整行空格 */
                        putchar(' ');
                        if (i % NLINE == 0)
                            putchar('\n');
                    }
                nspace -= nspace / NLINE * NLINE;    /* 减去输出的空白符 */
                len = nspace;
            }
        }
    }

    return 0;
}


你可能感兴趣的:(kr,2nd,1-22)