Implement a C beautifier program. Following beautifications are needed.a. Tab is replaced by 4 spacesb. After every starting brace ie. {, the next statement will start 4 spaces away from the starting of the line that contains opening brace.Example 1:#include <stdio.h> main() /* Hello there */{ int x = 0;/* This is a comment */while (x< 10) { x ++; } if (x) { x++; } else { y = 0; } } Expected output:#include <stdio.h> main() /* Hello there */{ int x = 0; /* This is a comment */ while(x<10) { x ++; } if(x) { x++; } else { y=0; } }
4,448 Views |
What’s there in this. Whenever you encounter a tab replace it with 4 spaces in the output file. Whenever you encounter a brace follow it with 4 spaces.
Keep a variable called tab+spaces in your code. You also have to care about indentation when you encounter braces.
So, replace all tabs by new line and tab_spaces (intially equal to 4).
Once you encounter a bracket, then increment the tab_spaces by 4. When you encounter a closing bracket, decrement a tab_space by 4.
Note that my assumption is that the code is complete and correct. In order to consider a situation when the code may not be correct, you can use a stack to keep track of opening and closing brackets.
Leave an Answer/Comment