首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将代码写入缩进代码

将代码写入缩进代码
EN

Stack Overflow用户
提问于 2015-05-03 15:49:18
回答 2查看 6.8K关注 0票数 3

我的目标是编写一个C程序,缩进char *input中给出的C代码。在字符串const char *pad中给出了一个级别缩进的样式。我编写了下面的代码,它在我的脑海中找到了,但在实践中却没有。一定是哪里出了错,但我找不到。另外,我也不明白为什么瓦伦不喜欢包含时间(.)的行。1码的无效读数..。

任何{都会将缩进级别增加一个,而任何}都会将缩进级别降低一个。不应用其他缩进规则。我假设字符串文本中没有花括号。

代码语言:javascript
复制
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;
}

而不是:

代码语言:javascript
复制
int main(void) {
    printf("asdfasdf\n");
    while (1)
    {
        while (2) {
            printf("printsomething\n");
        }
    }
}

我的准则是:

代码语言:javascript
复制
int main(void) {
        printf("asdfasdf\n");
        while (1)
        {
            while (2) {
                printf("printsomething\n");
            }
            }
            }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-03 16:31:39

在您试图编写的代码美化器中,您必须使用:

  • 燕子(不输出)一行中的所有初始空格(跟随\n)
  • 用适当的缩进代替它们,就像您根据{}的数目计算的那样

实现它,并问这里,如果你不能使它工作

票数 3
EN

Stack Overflow用户

发布于 2015-05-03 16:35:05

改变你的路线

代码语言:javascript
复制
n = ondx;

代码语言:javascript
复制
n = ndx + 1;

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30015876

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档