In the below program, i and l diverge when the input string contains a tab. i is a counter to iterate the Buffer and l is a counter that keeps track of chars put to the output stream. For example, in the following use case: abc\tdef\t\tghi\t\t\tjkl\tmno\n , where \t is tab, i and l will both increment at the same rate until the outer for loop in main hits the tab, then l increases faster than i, since more spaces are put in output stream for each tab in the Buffer.
That leads to my question: **I don't see a sequence pattern here**. It seems like if tabs are put in different places or there are multiple tabs one after the other, you are going to get different results. For example, in the above use case, when the first tab is hit, two spaces are printed (e.g. l is equal to 3 and 3 / 5 (TabSize) has a remainder of 3, and subtracting 5 - 3 returns 2). Another time, the CalculateNumberOfSpaces function returns 5. I tried different use cases, and they are all producing different results depending on where tab is and if multiple tabs are adjacent.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUFFER 1024
#define SPACE ' '
#define TAB '\t'
int CalculateNumberOfSpaces(int Offset, int TabSize)
{
return TabSize - (Offset % TabSize);
}
/* K&R's getline() function from p29 */
int getline(char s[], int lim)
{
int c, i;
for(i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if(c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
int main(void)
{
char Buffer[MAX_BUFFER];
int TabSize = 5; /* A good test value */
int i, j, k, l;
while(getline(Buffer, MAX_BUFFER) > 0)
{
for(i = 0, l = 0; Buffer[i] != '\0'; i++)
{
if(Buffer[i] == TAB)
{
j = CalculateNumberOfSpaces(l, TabSize);
for(k = 0; k < j; k++)
{
putchar(SPACE);
l++;
}
}
else
{
putchar(Buffer[i]);
l++;
}
}
}
return 0;
}
|
Is this using some kind of pattern sequence that I don't see? And when I say pattern sequence I mean something like you do in algebra:
1 2
|
f(n) = 3(n - 1) + 2
// 2,5,8,11,14,17,20,23,...
|
This program is taken from exercise guide in "C Programming language" book:
http://users.powernet.co.uk/eton/kandr2/krx120.html