编写缩进代码的代码

3
我的目标是编写一个C程序,对给定的char *input进行缩进。一级缩进的样式在字符串const char *pad中给出。我写了下面的代码,在我的头脑中可以工作,但在实践中却不能。肯定有哪里出错了,但我找不到它。 另外,我想不出为什么Valgrind不喜欢包含while(...)的那一行。Invalid read of size 1...

任何一个{都会使缩进级别增加一级,而任何一个}都会将缩进级别减少一级。不应用其他缩进规则。我假设字符串字面值中没有花括号。
char *indent(char *input, const char *pad)
{
    int lenpad = strlen(pad);
    int inlen = strlen(input);
    char *output = malloc(inlen+lenpad*90); //Here I'm praying +lenpad*90 is enough
    int indent = 0; 
    int i = 0;
    int j = 0;
    int ndx;
    int ondx;
    char current = 'a';
    int n;

    for(ndx=ondx=0; ndx<inlen; ndx++){
        current = input[ndx];
        if(current == '{') indent++;
        if(current == '\n'){
            output[ondx++] = '\n';
            n = ondx;
            while(input[n] != '\n' && input[n] != '\0'){ //Trying to check if the line to come has a curly bracket.
                if(input[n] == '}') //If it does, don't indent that line anymore.
                    indent--;
                n++;
            }
            for(j=0; j<indent; j++){
               for(i=0; i<lenpad; i++){
                output[ondx++] = pad[i];
                } 
            }
        }
        else{
            output[ondx++] = current;
        }
    }
    free(input);
    output[ondx] = '\0';
    return output;
}

改为:

int main(void) {
    printf("asdfasdf\n");
    while (1)
    {
        while (2) {
            printf("printsomething\n");
        }
    }
}

我的代码输出:

int main(void) {
        printf("asdfasdf\n");
        while (1)
        {
            while (2) {
                printf("printsomething\n");
            }
            }
            }

2
你想写这个的原因是什么,而不是使用其中一个代码美化工具呢? - Steve
3
我在祈祷+lenpad+90足够了” 不,我拒绝登上这架飞机。 - alk
5
为了避免误解,我认为这是一项不错的练习! :-) 但正因为如此,你应该自己解决它。百分之百。真的。 - alk
2
通过在 indent--; 这一行(在条件语句内部)设置断点,我们可以看到 这一行 从未被执行。 - user12205
2
谢谢提醒。我终于注意到我写成了 n = ondx 而不是使用 ndx。仔细看了三个小时后,我简直不敢相信自己没有找到这个错误。剩下的错误我会稍后或明天试图修复,因为它仍然存在问题。 - Zora
显示剩余2条评论
2个回答

3
在你正在尝试编写的代码美化器中,你必须

  • 吞掉(不输出)每行开头的所有空白字符(在\n之后)
  • 通过从{}数量计算出正确的缩进来替换它们

实现它,如果不能正常工作,请在此处提问。


我已经让代码正常工作了。现在我只需要实现你建议的内容。我会尝试去实现它。 - Zora
在Ace和你的帮助下,我成功地让它正常工作了!感谢你把我引导到正确的方向。 :) - Zora

2

更换你的线路

n = ondx;

为了

n = ndx + 1;

您希望n成为输入中下一个项目的索引,而不是输出的索引。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接