Exercise 1-20 (detab - Tabs to spaces)

Chapter_1     Exercise_1-19     Extern_longest_line Exercise_1-21







Exercise 1-20     K&R, p. 34


Exercise 1-20. Write a program detab that replaces tabs in the input with the proper number of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n columns. Should n be a variable or a symbolic parameter?




detab.c         download


#include <stdio.h> // for getchar(), putchar(), EOF

#define TAB 4 // 4 spaces
// For every chunk of TAB chars,
// detab("abc\t") == "abc " // 1 space
// detab("ab\t") == "ab " // 2 spaces
// detab("a\t") == "a " // 3 spaces
// detab("\t") == " " // 4 spaces

int main()
{
int c, i;
int count = 0; // count up to TAB chars (next tab stop)

while((c = getchar()) != EOF)
{
if (c == '\n')
{
count = 0; // reset, go to next line
putchar(c); // putchar('\n');
}
else if (c == '\t') // advance to next TAB stop
{
for (i = 0; i < TAB-count; i++)
{putchar(' ');} // add spaces up to next TAB stop
count = 0; // reset, go to next chunk of TAB chars
}
else
{
putchar(c);
count++;
if (count >= TAB) // if (count == TAB)
{count = 0;} // reset, go to next chunk of TAB chars
}
}

return 0;
}
/*
gcc detab.c -o detab
./detab // input from the keyboard
// For TAB == 8 on my computer (tabs separate the numbers):
1234567 123456 12345 1234 123 12 1 0 // Enter (tabs)
1234567 123456 12345 1234 123 12 1 0 // spaces
// Ctrl^D or Ctrl^C in Linux, Ctrl^Z + Enter in Windows (EOF)

./detab < detab.c // input from source file

./detab < detab // input from binary file
*/





Notes:

The size of the tab varies depending on the operating system, environment, or text editor you use. Usually is 4 or 8 characters long. The tab size can be specified as a command line argument or can be input at runtime with scanf(), both to be studied in the following chapters — Chapter_5 (Sec. 5.10), Chapter_7 (Sec. 7.4).
getline() would only work if it could retrieve arbitrarily long lines. Alternatively, we could use a function like ungetch(), see Chapter_4 (Sec. 4.3), to push the last read char back on input (when getline() stops before reaching newline).









Chapter_1     Exercise_1-19     Ext_long_line BACK_TO_TOP Exercise_1-21



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo