I am trying to make a program that converts 4 spaces to tabs. But I have some bug I can't find.
Here is the code:
#include <stdio.h>
#define TABVALUE 4
#define ARRAYSIZE 3
int c, d, s;
int savedChars[ARRAYSIZE];
void emptyArray(int *a);
int main(void) {
c = s = d = 0;
while ((c = getchar()) != EOF) {
if (c == ' ') {
s = 0;
s++;
for (int j = 0; j < TABVALUE - 1; j++) {
d = getchar();
if (d != EOF) {
savedChars[j] = d;
savedChars[j + 1] = '\0';
if (d == ' ') {
s++;
} else {
break;
}
}
}
if (s == TABVALUE) {
emptyArray(savedChars);
putchar('\t');
s = 0;
} else {
putchar(c);
for (int i = 0; i < 3; i++) {
if (savedChars[i] != '\0') {
putchar(savedChars[i]);
}
}
}
} else {
if (c != EOF) putchar(c);
}
}
return 0;
}
void emptyArray(int *a) {
for (int i = 0; i < ARRAYSIZE; i++) {//The bug is not in this function, i guess
a[i] = '\0';
}
}
Input:
2 spaces then character d 4 spaces then character d
Output:
2 spaces then character d 1 space then character d
But when I just add putchar(s)
or anything like printf("a")
before:
if (s == TABVALUE) {
emptyArray(savedChars);
putchar('\t');
s = 0;
}
than the output is this:
a 2 spaces d a tab d
Why is tab working when I print something? I am really confused...