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