Advertisement
Guest User

Untitled

a guest
Feb 26th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.69 KB | None | 0 0
  1. {string}        {
  2.  
  3.     char c;
  4.     int i, error, lookahead;
  5.     i = 0; /* the string index the next character will be placed at */
  6.     error = 1; /* flag that keeps track of the string's proper closure */
  7.     lookahead = 0; /* set when looking ahead for special characters */
  8.     char * s = malloc(2 * sizeof(char));
  9.     *(s + i) = '\0';
  10.     while ((c = input()) != EOF)
  11.     {
  12.         if (lookahead == 1)
  13.         { /* we've already checked this character, move on */
  14.             lookahead = 0;
  15.             continue;
  16.         }
  17.         if (c == '\\')
  18.         { /* check the next character to see if it's special */.
  19.             c = input();
  20.             lookahead = 1;
  21.             if (c == 'n')
  22.             { /* newline */
  23.                 *(s + i) = '\n';
  24.             }
  25.             else if (c == 't')
  26.             { /* tab */
  27.                 c = '\t';
  28.                 *(s + i) = c;
  29.             }
  30.             else if (c == '\\')
  31.             { /* backslash */
  32.                 *(s + i) = '\\';
  33.             }
  34.             else if (c == '\"')
  35.             { /* double quotation mark */
  36.                 *(s + i) = '"';
  37.             }
  38.             else if (c == '\'')
  39.             { /* single quotation mark */
  40.                 *(s + i) = '\'';
  41.             }
  42.             else
  43.             { /* unknown character */
  44.                 *(s + i) = '\\';
  45.                 i++;
  46.                 *(s + i) = c;
  47.                 printf("Error: Unknown escape character found in string\n");
  48.             }
  49.         }
  50.         else if (c == '\"')
  51.         { /* end of string */
  52.             *(s + i) = '\0';
  53.             head = add_token(head, yylineno, ++token, "STRING", s);
  54.             error = 0;
  55.             break;
  56.         }
  57.         else
  58.         { /* normal character */
  59.             *(s + i) = c;
  60.         }
  61.         i++;
  62.         s = realloc(s, (i + 2) * sizeof(char));
  63.         *(s + i) = '\0';
  64.     }
  65.     if (error == 1)
  66.     {   /* the string wasn't closed properly */
  67.         /* thus, we're not going to store it as a token */
  68.         printf("Error: Unclosed string %s at line %d", s, yylineno);
  69.     }
  70.     free(s);
  71. /*end of string code*/
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement