British0zzy
July 18th, 2008, 03:28 AM
I don't know if this question is too 'beginner' to ask in this forum, but I have a problem I can't diagnose.
I'm writing a program that removes tabs from the input and replaces it with the correct number of spaces. It's giving me odd results, which I can't quite figure out why. If you could look at this short program and give me some pointers, it'd be greatly appreciated.
#include <stdio.h>
#define TABLENGTH 4
main()
{
int n; /* Position of cursor relative to tab stops */
int c;
n = TABLENGTH; /* Setting n to TABLENGTH is functionally equivalent to setting it to zero, but will make calculations easier */
while ((c=getchar()) != EOF) {
if (n > TABLENGTH) /* When the cursor reaches a tab stop, reset the position. */
n = 1; /* Should this be n = n - TABLENGTH? */
if (c != '\t') {
putchar(c);
if (c == '\n')
n = TABLENGTH; /* A newline resets the cursor to 'zero' */
else
++n;
}
else {
for (c = 0; c < n; ++c)
putchar(' ');
n = TABLENGTH; /* Tabs reset cursor to 'zero' */
}
}
return 0;
}
I'm writing a program that removes tabs from the input and replaces it with the correct number of spaces. It's giving me odd results, which I can't quite figure out why. If you could look at this short program and give me some pointers, it'd be greatly appreciated.
#include <stdio.h>
#define TABLENGTH 4
main()
{
int n; /* Position of cursor relative to tab stops */
int c;
n = TABLENGTH; /* Setting n to TABLENGTH is functionally equivalent to setting it to zero, but will make calculations easier */
while ((c=getchar()) != EOF) {
if (n > TABLENGTH) /* When the cursor reaches a tab stop, reset the position. */
n = 1; /* Should this be n = n - TABLENGTH? */
if (c != '\t') {
putchar(c);
if (c == '\n')
n = TABLENGTH; /* A newline resets the cursor to 'zero' */
else
++n;
}
else {
for (c = 0; c < n; ++c)
putchar(' ');
n = TABLENGTH; /* Tabs reset cursor to 'zero' */
}
}
return 0;
}