我正在尝试编写 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/