10
2
Write a program that adds or removes whitespace to format code nicely. Rules for what the code should look like when you're done:
- No line should contain more than one of
{
and}
. - A
{
should always be the last thing on a line. - A
}
should always be the only thing on a line (besides whitespace that comes before it). - The amount of whitespace in front of each line should be a fixed multiple of the current nesting count. (You can use any amount of indentation you want, as long as it doesn't change.)
- No whitespace should be inserted or removed that doesn't contribute to satisfying one of these rules.
The nesting count for the first line is 0. The nesting count of any other line is the nesting count of the previous line, plus one if the previous line contains a {
, minus one if the current line contains a }
.
{
and }
inside string literals and comments don't count in the above rules. A string literal is text enclosed in single or double quotes, where single or double quotes with an odd number of backslashes immediately before them aren't interpreted as the end of the string literal. A comment is text enclosed in /*
and */
, or text going from //
to the end of the line. In a line multiple comment start markers, only the first one counts. Comments are not parsed inside string literals.
Examples
main() {printf("Hello!"); // I don't care about the world...
}
becomes:
main() {
printf("Hello!"); // I don't care about the world...
}
int main(){
puts("a");
puts("b");
}
becomes:
int main(){
puts("a");
puts("b");
}
main()
{ printf("{"); /* }
} */
printf("}//}"); ///*
}
becomes:
main()
{
printf("{"); /* }
} */
printf("}//}"); ///*
}
int test[] = {1, 2, 3};
becomes:
int test[] = {
1, 2, 3
}
;
Comments are not for extended discussion; this conversation has been moved to chat.
– Dennis – 2017-06-30T06:02:07.953