
Untitled
By: a guest on
May 5th, 2012 | syntax:
None | size: 2.42 KB | hits: 9 | expires: Never
## Example 1.21 - Convert any string of blanks into minimum number of tabs and spaces
#include <stdio.h>
#define TAB_STOP 8 /* the number of columns between each tab stop */
#define SPACE ' ' /* set to visible character (ex. '-') for debug */
#define BLANK 1 /* inside a blank space */
#define NOT_BLANK 0 /* inside visible characters (not blank) */
/* replace all strings of blanks in the input with the minimum
* number of tabs and spaces to achieve the same spacing */
int main()
{
int c, col, tab_length, blank_length, potential_tab_length, state;
col = 0; /* number of columns covered */
blank_length = 0; /* length of the current string of blanks (in cols) */
while((c = getchar()) != EOF)
{
if(c == '\n') col = -1; /* reset column count at end of each line */
if(c == ' ' || c == '\t') /* set state to blank whenever a blank character is encountered */
{
state = BLANK;
}
else /* if a non-blank character is encountered */
{
++col;
if(state == BLANK) /* if previously blank, show minimum number of tabs and spaces to cover blank space */
{
potential_tab_length = (TAB_STOP - ((col - blank_length - 1) % TAB_STOP));
while(blank_length - potential_tab_length >= 0)
{
putchar('\t');
blank_length = blank_length - potential_tab_length;
potential_tab_length = (TAB_STOP - ((col - blank_length - 1) % TAB_STOP));
}
while(blank_length != 0)
{
putchar(SPACE);
--blank_length;
}
blank_length = 0;
state = NOT_BLANK;
}
putchar(c);
}
if(state == BLANK) /* update blank_length and col counters */
{
if(c == ' ')
{
++blank_length;
++col;
}
else
{
tab_length = (TAB_STOP - (col % TAB_STOP));
blank_length = blank_length + tab_length;
col = col + tab_length;
}
}
}
return 0;
}