I am trying to write my solution for the KnR problem 1-22. Below is my code which I am not able to get why it's not working. It just prints the whole line that I typed, without folding.
#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;
}
Also, when I send EOF (^D) it again comes to read ,then I need to send EOF again to break it off. Why its not breaking first time I send EOF.
c=='\n';
should be c = '\n';
- Haven't checked to ensure that is the only issue...