# Thread: Detab Function Loop Hang

1. ## Detab Function Loop Hang

Hello, I'm a scheme programmer teaching myself C with the K and R book (what can I say, I'm bored with my Java OOP class). The end of chapter one asks you to write a function to replace all tabs with a set number of spaces. So I wrote the function below. Anyhow, the program works fine if I enter no tabs, but if I enter a tab it goes into a never ending loop.

Two questions:
1) Why
2) A *tip* on what a better way to solve this is

I know there are answers that can be found online, but they are not very helpful to a C-novice like myself because they do not explain precisely what they or are doing, or more importantly, why.

Code:
```void detab(char s[], char x[], int space)
{
int i;

i = 0;
while(s[i] != '\0')
{
if (s[i] == '\t') {
for(int y = space; y == 0; y--)
x[i+y] = ' ';

} else {
x[i] = s[i];
i++;
}
}
}

/** note: to compile this use: gcc -std=gnu99``` 2. A big problem is how the tab got there -- while there is a character '\t', if the string was supplied from keyboard input or from a text file, for example, it will be a number of spaces and cannot possibly be an actual '\t'. 3. A couple things.

1) You need two index variables. You can't do it with 1. One for s[] and one for x[]. Right now, you are losing the position in x[] since i is used for s[].
2) Your tab replacement FOR loop is bad. If there are 4 spaces to add, the largest offset you should use is 3, not 4. 4. In my opinion, transducer-like functions such as this are more easily understood using pointers rather than indexes.

Code:
```void detab(char s[], char x[], int space)
{
char *in = s;
char *out = x;
for(; *in; ++in)
{
if(*in == '\t')
for(int y = 0; y < space; ++y)
*out++ = ' ';
else
*out++ = *in;
}
*out = '\0';
}``` 5. Your code doesn't show the portion that reads input; and how many spaces make up a <TAB>? Post the entire code here.
Reason it's stuck in an infinite loop: the if statement doesn't increment i after you have replaced the <TAB> with spaces. 6. Variable in is updated 1 byte each time through the FOR loop. See ++in, so that's not the problem.

[EDIT] Sorry itCbitC - I was looking at brewbuck's code. I think the OP is long gone. 7. Code:
`for(int y = space; y == 0; y--)`
This for loop is all wrong - unless space is 0, it wont loop even once. If space is 0, it will loop once, then break the loop, with y = -1.

Look at brewbucks code for a correct loop.

--
Mats Popular pages Recent additions 