【问题标题】:C:folding a line after a fixed columnC:在固定列后折叠一行
【发布时间】:2013-10-17 05:37:21
【问题描述】:

我正在尝试为 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 时它没有中断。

【问题讨论】:

  • ^D 不是 EOF;但是,单独在一行上键入它会导致您的终端发送 EOF。如果您有任何内容,它只会清除缓冲区。是这样吗?
  • 如果当前字符是制表符怎么办?也是一个空间。使用例如isspace 判断一个字符是否为“空格”。
  • @CarlNorum 不知何故我不太清楚你在上面说什么。但是,如果我说得对,那么当我第二次按 ctrl+D 时它也不应该中断。

标签: c eof kernighan-and-ritchie


【解决方案1】:

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

【讨论】:

  • 你拯救了我的一天。这就是问题所在。!!虽然 EOF 的事情我仍然需要检查.. 几个小时后我有一个电话面试:D
  • 如果我解决了问题,您接受答案。祝面试顺利!
猜你喜欢
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多