我正在尝试为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 - C:在固定列后折行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19419015/