Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Exercise 1-24. Write a program to check a C program for rudimentary syntax errors like unmatched parentheses, brackets and *braces. Don't forget about quotes, both single and double, escape sequences, and comments. (This program is hard if you do it in full generality.)*/
- #include <stdio.h>
- #define MAX 1000
- char str[MAX];
- int rud(int len);
- int main()
- {
- int ret;
- ret = rud(MAX);
- return 0;
- }
- int rud(int len) {
- int c, i, lc;
- int parentheses, braces, brackets, quotes, dquotes, parentheses_line, brace_line, bracket_line;
- i = lc = parentheses = braces = brackets = quotes = dquotes = brace_line = bracket_line = parentheses_line = 0;
- while ((c = getchar()) != EOF && i < len - 1 ) {
- if (c == '\n') {
- lc++;
- if ((quotes % 2) != 0)
- printf ("line %d has unclosed quotes\n", lc);
- if ((dquotes % 2) != 0)
- printf ("line %d has unclosed double quotes\n", lc);
- if (!parentheses)
- parentheses_line = 0;
- if (!braces)
- brace_line = 0;
- if (!brackets)
- bracket_line = 0;
- quotes = dquotes = 0;
- }
- if (c == '\'')
- quotes++;
- if (c == '"')
- dquotes++;
- if (c == '(') {
- braces++;
- brace_line = lc;
- brace_line++;
- }
- if (c == '[') {
- brackets++;
- bracket_line = lc;
- bracket_line++;
- }
- if (c == '{') {
- parentheses++;
- parentheses_line = lc;
- }
- if (c == ')')
- braces--;
- if (c == ']')
- brackets--;
- if (c == '}')
- parentheses--;
- str[i++] = c;
- }
- if (parentheses)
- printf ("line %d has unclosed parentheses\n", parentheses_line);
- if (braces)
- printf ("line %d has unclosed braces\n", brace_line);
- if (brackets)
- printf ("line %d has unclosed brackets\n", bracket_line);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment