Created
February 1, 2017 05:16
-
-
Save ethagnawl/2cb642f164e05ada0a5f330bb7052f73 to your computer and use it in GitHub Desktop.
Fold Long Lines - K&R 1-22
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This was my attempt at K&R 1-22 | |
// Though, this implementation has a bug wherein the last word of a short line is always printed on its own line. This is because | |
// there's currently no way for the program to know when the "split" word would fit on the current line. | |
// This solution is nice because it will work with arbitrarily long lines. | |
// The lines are read-in (80 chars or less at a time), the last space is sniffed out, then the last word is split, | |
// a newline is printed, and the "split" word is printed. On the next loop, the get_line function ends N chars from | |
// the line break, in order to acommodate the "split" word which has already been printed on the current line. | |
#include <stdio.h> | |
#define MAX_LINE_LENGTH 80 | |
// This is copied straight from the book, but the name is not intention | |
// revealing at all. | |
int get_line(int tail, char input[], int maximum_line_length) { | |
int c, | |
i, | |
j; | |
for (i = 0; i < (maximum_line_length - tail - 1) && | |
(c = getchar()) != EOF && | |
c != '\n'; ++i) { | |
input[i] = c; | |
} | |
if (c == '\n') { | |
input[i++] = c; | |
} | |
input[i] = '\0'; | |
return i; | |
} | |
int main() { | |
int i, | |
j, | |
k, | |
last_space, | |
line_length, | |
tail; | |
char line[MAX_LINE_LENGTH]; | |
while ((line_length = get_line(head, line, MAX_LINE_LENGTH)) > 0) { | |
for (i = 0; i < line_length; ++i) { | |
if (line[i] == ' ') { | |
last_space = i; | |
} | |
} | |
for (j = 0; j < last_space; ++j) { | |
putchar(line[j]); | |
} | |
tail = line_length - last_space - 1; | |
printf("\n"); | |
for (k = 0; k <= tail; ++k) { | |
putchar(line[line_length - tail + k]); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment