简体   繁体   English

如何使用 c++ 调整文本文件中代码的缩进?

[英]How to adjust the indentation of code in text file using c++?

I am copying code of file 1 to file 2, but i want the code in file 2 to look adjusted with indentation like this: at the beginning indentation=0, every curly bracket opened increases the depth of indentation, every curly bracket closed reduces the indentation 4 spaces for example.我正在将文件 1 的代码复制到文件 2,但我希望文件 2 中的代码看起来像这样调整缩进:在开始缩进 = 0 时,打开的每个大括号都会增加缩进的深度,关闭的每个大括号都会减少例如缩进 4 个空格。 I need help in fixing this to work我需要帮助来解决这个问题

char preCh;
int depth=0;
    int tab = 3;
    int d = 0;
    int pos = 0;
    file1.get(ch);
    while(!file1.eof())
    {
            if(ch=='{')
            {
                d++;
            }
            if(ch=='}'){
                d--;
            }
            depth = tab * d;
            if(preCh == '{' && ch=='\n'){
            file2.put(ch);
                for (int i = 0; i <= depth; i++)
                {
                     file2.put(' ');
                }
            }
                else
                file2.put(ch);
        preCh = ch;
        ch = file1.get();
    }
}

result must be indented like in code editors:结果必须像在代码编辑器中一样缩进:

int main(){ 
    if(a>0)
    {
       something();
    }
}

Maybe, unexpectedly for you, there is no easy answer to your question.也许,出乎你意料的是,你的问题没有简单的答案。

And because of that, your code will never work.因此,您的代码将永远无法工作。

First and most important, you need to understand and define indentation styles.首先也是最重要的,您需要了解和定义缩进 styles。 Please see here in Wikipedia .请在Wikipedia中查看此处。 Even in your given mini example, you are mixing Allman and K&R.即使在您给定的迷你示例中,您也在混合 Allman 和 K&R。 So, first you must be clear, what to use.所以,首先你必须清楚,用什么。

Then, you must be aware that brackets may appear in quotes, double quotes, C-Comments, C++ comments and even worse, multi line comments (and #if or #idefs).然后,您必须注意括号可能出现在引号、双引号、C 注释、C++ 注释中,甚至更糟糕的是,多行注释(以及#if 或#idefs)。 This will make life really hard.这会让生活变得非常艰难。

And, for the closing brackets, and for example Allman style, you will know the needed indentation only after you printed already the "indentation spaces".而且,对于右括号,例如 Allman 样式,只有在打印了“缩进空间”之后,您才会知道所需的缩进。 So you need to work line oriented or use a line buffers, before you print a complete line.因此,在打印完整行之前,您需要面向行工作或使用行缓冲区。

Example:例子:

    }

In this one simple line, you will read the '}' character, after you have already printed the spaces.在这一简单的行中,您将在打印空格后读取“}”字符。 This will always lead to wrong (too far right) indentation.这总是会导致错误的(太右)缩进。

The logic for only this case would be complicated.只有这种情况的逻辑会很复杂。 Ant then assume statements like Ant 然后假设语句如

if (x ==5) { y = 3; } } } }

So, unfortunately I cannot give you an easy solution.所以,不幸的是我不能给你一个简单的解决方案。

A parser would be needed, or I simply recommend any kinde of beautifier or pretty printer需要一个解析器,或者我只是推荐任何一种美化器或漂亮的打印机

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM