Like many others, I'm teaching myself C via K&R and am having a lot of trouble with exercise 1-20, the detab program. My code almost does exactly what I want it to, but the difference is inexplicable. It correctly inserts the number of spaces to replace the tabs; however, it treats the first tab as being 8 characters, but all others as 7. I've poured over the issue for hours; I've even downloaded solutions online and run them, without ever seeing what the problem with my code is.. (Some didn't even work; all implemented the program somewhat differently than I.)
Would someone please point in the right direction? I appreciate all assistance.
Here's the code; I'm compiling with a simple "gcc -o detab detab.c", on GNU/Linux kernel 2.6.26, with gcc version 4.3.2. Debian Lenny.
Code:
#include <stdio.h>
#define TABSTOP 8
#define MAXLINE 10000
int getline(char s[], int lim);
int tabber(char s[], int tabspot);
main()
{
char string[MAXLINE];
int i, realspot = 0;
while (getline(string, MAXLINE) > 0) {
for(i=0,realspot=0; string[i] != '\0'; ++i,++realspot)
if (string[i] == '\t')
realspot += tabber(string,realspot);
else
putchar(string[i]);
}
return 0;
}
int tabber(char s[], int tabspot)
{
int numspace, i;
numspace = TABSTOP - (tabspot % TABSTOP);
for (i=0; i<numspace; ++i)
putchar('_');
return numspace;
}
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;
s[i] = '\0';
return i;
}