From b6b22b5c5acbe317d7ad992b58169b0678e64a9a Mon Sep 17 00:00:00 2001 From: zlg Date: Thu, 29 Nov 2012 14:44:25 -0600 Subject: 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 --- 1-21_entab.c | 43 +++++++++++++++++++++++++++---------------- 1 file changed, 27 insertions(+), 16 deletions(-) (limited to '1-21_entab.c') 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); } } -- cgit v1.2.3-54-g00ecf