/* Parser code for input SBVs. * * The next_token function breaks up the input stream so that * you can load it into the SBV. Recalling that a list is stored * as a string "( Item1 Item2 Item3 )", the tokenizer takes this string * and breaks it into tokens. A token is either a "(", ")" or a string * containing no whitespace and no parentheses. * * IMPORTANT NOTES: * - The tokenizer does NOT check to see if the STRING represents an * integer. You will have to write code to check this. * * - To convert a string to an integer, you can use the atoi(char []) * function. * */ #include #include #include #include // BEGIN CODE FOR THE PARSER enum TOKEN { LEFT_PAR, RIGHT_PAR, STRING, END, ERROR }; void next_token(istream &is, TOKEN &token_type, char *buf, int max_buf); /* Get next token from buffer. max_buf is the size of the buffer buf. * Post Conditions: * token_type = LEFT_PAR : current token is a '(', buf = "(" * token_type = RIGHT_PAR : current token is a ')', buf = ")" * token_type = STRING : current token is a string not containing any white space nor parentheses. buf contains this string * token_type = END : the tokenizer has reached the end of the buffer. buf is unchanged * token_type = ERROR : the tokenizer experienced an error. the most common error is that buf is too small to contain the current token. the data in buf is unpredictable and should not be used. */ void next_token(istream &is, TOKEN &token_type, char *buf, int max_buf) { char c; while ((is.get(c)).good() && isspace(c)); if (is.eof()) { token_type = END; return; } if (is.fail()) { token_type = ERROR; return; } if (c == '(') { token_type = LEFT_PAR; return; } if (c == ')') { token_type = RIGHT_PAR; return; } do { if (max_buf-- <= 1) { token_type = ERROR; return; } *(buf++) = c; } while ((is.get(c)).good() && !isspace(c) && c != '(' && c != ')'); if (!is.eof() && is.fail()) { token_type = ERROR; return; } if(!is.eof()) is.putback(c); token_type = STRING; *buf = '\0'; } // END CODER FOR THE PARSER int main() { ifstream fin; fin.open("list.data"); TOKEN tt=ERROR; char s[10]; int i=0; while(tt!=END && i<30) { i++; next_token(fin,tt,s,10); if(tt==LEFT_PAR) cout << "LEFT (\n"; else if(tt==RIGHT_PAR) cout << "RIGHT )\n"; else if(tt==ERROR) cout << "ERROR\n"; else if(tt==STRING) { int x = atoi(s); // NOTE atoi( ) for converting string to int cout << x << endl; } } return 0; }