samir82show

c_ch01_ex24.c

Nov 8th, 2014
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. /*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.)*/
  2. #include <stdio.h>
  3. #define MAX 1000
  4. char str[MAX];
  5. int rud(int len);
  6. int main()
  7. {
  8. int ret;
  9. ret = rud(MAX);
  10. return 0;
  11. }
  12. int rud(int len) {
  13. int c, i, lc;
  14. int parentheses, braces, brackets, quotes, dquotes, parentheses_line, brace_line, bracket_line;
  15. i = lc = parentheses = braces = brackets = quotes = dquotes = brace_line = bracket_line = parentheses_line = 0;
  16. while ((c = getchar()) != EOF && i < len - 1 ) {
  17. if (c == '\n') {
  18. lc++;
  19. if ((quotes % 2) != 0)
  20. printf ("line %d has unclosed quotes\n", lc);
  21. if ((dquotes % 2) != 0)
  22. printf ("line %d has unclosed double quotes\n", lc);
  23. if (!parentheses)
  24. parentheses_line = 0;
  25. if (!braces)
  26. brace_line = 0;
  27. if (!brackets)
  28. bracket_line = 0;
  29. quotes = dquotes = 0;
  30. }
  31. if (c == '\'')
  32. quotes++;
  33. if (c == '"')
  34. dquotes++;
  35. if (c == '(') {
  36. braces++;
  37. brace_line = lc;
  38. brace_line++;
  39. }
  40. if (c == '[') {
  41. brackets++;
  42. bracket_line = lc;
  43. bracket_line++;
  44. }
  45. if (c == '{') {
  46. parentheses++;
  47. parentheses_line = lc;
  48. }
  49. if (c == ')')
  50. braces--;
  51. if (c == ']')
  52. brackets--;
  53. if (c == '}')
  54. parentheses--;
  55. str[i++] = c;
  56. }
  57. if (parentheses)
  58. printf ("line %d has unclosed parentheses\n", parentheses_line);
  59. if (braces)
  60. printf ("line %d has unclosed braces\n", brace_line);
  61. if (brackets)
  62. printf ("line %d has unclosed brackets\n", bracket_line);
  63. return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment