jeudi 4 mars 2021

Is it possible to write 'else if' N times with for loop?

I'm writing an entab program which is K&R exercise.

Exercise 1-21. Write a program entab that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing.

My solution is dividing each line by N character(where 1 tab == N whitespace) and checking from the rightmost character to the first character whether it is whitespace character or not.

#include <stdio.h>

void entab(int n);

int main(void)
{
    entab(8);
}

void entab(int n) // n should be at least 2
{
    int c;
    int i, j;
    int temp[n];

    while (1) {

        // Collect n characters
        // If there is EOF, print all privious character and terminate the while loop.
        // If there is new line character, print all privious and current character, then continue the while loop again.
        for (i = 0; i < n; ++i) {
            temp[i] = getchar();
            if (temp[i] == EOF) {
                if (i > 0)
                    for (j = 0; j < i; ++j)
                        putchar(temp[j]);
                break;
            }
            else if (temp[i] == '\n') {
                for (j = 0; j <= i; ++j)
                    putchar(temp[j]);
                break;
            }
        }

        if (temp[i] == EOF)
            break;
        if (temp[i] == '\n')
            continue;

        // the temp array has exactly 8 characters without newline character and EOF indicator.
        // check a continuity of the whitespace character and put the tab character at the right space.
        if (temp[n-1] != ' ') {
            for (i = 0; i <= n-1; ++i)
                putchar(temp[i]);
        }
        for (j = n-2; j >= 0; --j) {
            else if (temp[j] != ' ') {
                for (i = 0; i <= j; ++i)
                    putchar(temp[i]);
                putchar('\t');
            }
        }
        else
            putchar('\t');
    }
}

This part makes sense but is syntactically not allowed. But I have to use a loop syntax because I want the program to entab a arbitrary number of the whitespace character.

if (temp[n-1] != ' ') {
    for (i = 0; i <= n-1; ++i)
        putchar(temp[i]);
}
for (j = n-2; j >= 0; --j) {
    else if (temp[j] != ' ') {
        for (i = 0; i <= j; ++i)
            putchar(temp[i]);
        putchar('\t');
    }
}
else
    putchar('\t');

I tried a function-like macro but it didn't make significant difference. Is it just impossible? Should I consider another design or logic?

Aucun commentaire:

Enregistrer un commentaire