aboutsummaryrefslogtreecommitdiff
path: root/1-21_entab.c
diff options
context:
space:
mode:
authorzlg <zlg@zlg.space>2012-11-29 14:44:25 -0600
committerzlg <zlg@zlg.space>2012-11-29 14:44:25 -0600
commitb6b22b5c5acbe317d7ad992b58169b0678e64a9a (patch)
treedf8e968e05d8fd85d88c5f1db6cda37fb152aa84 /1-21_entab.c
parentCorrect 1-13's chart heading (diff)
downloadknr-b6b22b5c5acbe317d7ad992b58169b0678e64a9a.tar.gz
knr-b6b22b5c5acbe317d7ad992b58169b0678e64a9a.tar.bz2
knr-b6b22b5c5acbe317d7ad992b58169b0678e64a9a.tar.xz
knr-b6b22b5c5acbe317d7ad992b58169b0678e64a9a.zip
Clean up 1-13 and 1-20, correct 1-21
1-13 uses less variables and a for loop for the chart header 1-20 has minor changes 1-21 was rewritten to behave properly README has been rewritten to reflect the limitations of my solutions
Diffstat (limited to '1-21_entab.c')
-rw-r--r--1-21_entab.c43
1 files changed, 27 insertions, 16 deletions
diff --git a/1-21_entab.c b/1-21_entab.c
index 0f25706..6037a14 100644
--- a/1-21_entab.c
+++ b/1-21_entab.c
@@ -15,30 +15,41 @@
#define TABWIDTH 8
int main(void) {
- int c, spaces;
- spaces = 0;
+ int column, c, spaces;
+ spaces = column = 0;
while ((c = getchar()) != EOF) {
- // Make sure the character is a space...
+ // First thing's first, advance by a column.
+ column++;
+
if (c == ' ') {
- ++spaces;
- // When spaces is equal to TABWIDTH, we can add a tab
- if (spaces == TABWIDTH) {
+ /* Add to 'spaces' immediately, we'll decide if it needs to be
+ * output later.
+ */
+ spaces++;
+
+ if (column % TABWIDTH == 0 && spaces > 0) {
putchar('\t');
- spaces = 0;
+ spaces = 0; // No spaces are left when we tab!
}
+
} else {
- /* As soon as we hit a non-space character, we need to make sure
- * there aren't 1-7 spaces leftover. These need to be output before
- * we output the non-space character itself! This little loop is
- * interesting because it solves the problem of leftover spaces
- * _and_ gets the 'spaces' back to zero, which it needs to be once
- * we hit a non-space character.
+ /* Be sure to output any leftover spaces when we come across a
+ * non-space character. This should allow for spaces between words
+ * that don't fall along the tabstop lines.
*/
- while (spaces != 0) {
+
+ while (spaces > 0) {
putchar(' ');
- --spaces;
+ spaces--;
}
- // Output the non-space character.
+
+ // As usual, reset things on a newline.
+ if (c == '\n') {
+ column = 0;
+ spaces = 0;
+ }
+
+ // Now we can output whatever it is.
putchar(c);
}
}