简体   繁体   中英

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. 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. Please see here in Wikipedia . Even in your given mini example, you are mixing Allman and 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). 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". 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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