C:在固定列后折叠一行

标签 c eof kernighan-and-ritchie

我正在尝试编写 KnR 问题 1-22 的解决方案。下面是我的代码,我无法理解为什么它不起作用。它只是打印我输入的整行,而不折叠。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SPACE ' '
#define LIMIT 1024
#define BREAK 20
#define ON 1
#define OFF 0

int main(void) {
    /*base, is an offset from where the difference of current array position will be calculated*/
    int c,base=0,i,l_break=OFF;
    char s[LIMIT];
    for(i = 0; (c = getchar()) != EOF; ++i) {
        /*If break is on and space comes, turn the space into newline so that the line folds*/
        if(l_break==ON && c==SPACE) {
            c=='\n';
            base=i;
        }
        /*Breaking position is reached but not a blank position yet to break.*/
        if(((i-base)==BREAK) && c!=SPACE)
            l_break=ON;
        /*If user sends a newline explicitly(or space converted to newline above), reset the base*/
        if(c == '\n') {
            base=i;
            s[i] = c;
            l_break=OFF;
        } else
            s[i] = c;
    }
    s[i] = '\0';
    /*Print the final sentence after processing*/
    i=0;
    printf("\n");
    while(s[i]!='\0') {
        printf("%c",s[i]);
        ++i;
    }
    printf("\n");
    return 0;
}

另外,当我发送 EOF (^D) 时,它再次读取,然后我需要再次发送 EOF 来中断它。为什么我第一次发送 EOF 时没有中断。

最佳答案

c=='\n'; 应该是 c = '\n'; - 尚未检查以确保这是唯一的问题...

关于C:在固定列后折叠一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19419015/

相关文章:

c - 如何计算字符串中字符串的出现次数?

c - spi驱动中的基本设备操作

c - C程序控制台输入的奇怪现象

c - 在C编程中达到EOF时如何退出stdin

c - 为什么他们在 K&R 第 6.5 节中使用函数 strdup?

c - 在 C 中使用 typedef 定义的矩阵数组中访问元素的正确方法

c - 如何使用AC_CONFIG_SUBDIR 将C 和Fortran 库一起打包,其中C 依赖于Fortran 库?

c - 从 C 中的文件扫描

c - 程序可以编译,但在提供输入时不执行任何操作

c - K&R 1.21,打印数组时插入新行