首页 > 解决方案 > 是否可以使用 for 循环编写“else if”N 次?

问题描述

我正在编写一个作为 K&R 练习的 entab 程序。

练习 1-21。编写一个程序entab,用最少数量的制表符和空格替换空格字符串,以达到相同的间距。

我的解决方案是将每一行除以 N 个字符(where 1 tab == N whitespace)并检查从最右边的字符到第一个字符是否是空白字符。

#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');
    }
}

这部分是有道理的,但在语法上是不允许的。但我必须使用循环语法,因为我希望程序输入任意数量的空白字符。

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');

我尝试了一个类似函数的宏,但没有显着差异。这是不可能的吗?我应该考虑另一种设计或逻辑吗?

标签: cfor-loopif-statement

解决方案


推荐阅读