I'm looking for feedback on the code I came up with for exercise 1-21 in "The C Programming Language" by K&R.
Write a program entab that replaces strings of blanks with the minimum number of tabs and blanks to achieve the same spacing. Use the same stops as for detab . When either a tab or a single blank would suffice to reach a tab stop, which should be given preference?
The feedback I would mainly like is on readability, conventions and general good (or bad) practices.
This was a fun problem to solve and I think I came up with a efficient solution.
#include <stdio.h>
#define TABSIZE 8
#define MAXLENGTH 80
void entab(char s[]);
int _getline(char s[], int lim);
int main()
{
int len;
char line[MAXLENGTH];
while ((len = _getline(line, MAXLENGTH)) > 0)
entab(line);
}
void entab(char s[])
{
int i, c, nb;
nb = 0;
for (i = 0; (c = s[i]) != '\0'; ++i)
{
if (c == ' ')
{
if (++nb > 1)
{
if (i + 1 % TABSIZE == 0)
{
putchar('\t');
nb = 0;
}
}
}
else
{
if (nb > 0)
{
for (; nb > 0; --nb)
putchar('x');
}
putchar(c);
}
}
}
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;
}
The function _getline() was given by the book.
Only practices encountered in the book up until this assignment are used, I have not yet read about things like pointers and other more advanced features
My own thoughts
- Use (more) comments when coding
- Use more "self-explaining" variable names
- Input longer than 80 characters isn't handled correctly