void lex(ifstream& ifs) { // Reserve reserve(); // Vector of tokens in one statement (statement ends with semicolon) vector<Token> oneStmtToken; char current; while ( (current = ifs.get()) != EOF ) { int type = getType(current); if ( type == SPACE ) { // Ignore } else if ( type == DIGIT ) { // Get the actual number int v = 0; int startCol = _col; do { v = 10 * v + current - '0'; current = ifs.get(); } while ( getType(current) == DIGIT ); ifs.putback(current); revert(current); Token num(NUM, _line, startCol, v); oneStmtToken.push_back(num); } else if ( type == LETTER ) { // Get the id string buffer; int subType; int startCol = _col; do { buffer += current; current = ifs.get(); subType = getType(current); } while ( subType == LETTER || subType == DIGIT ); ifs.putback(current); revert(current); // If it is keyword int tag = symbol.find(buffer)->second.tag; if ( tag >= 256 && tag <= 269 ) { Token keyword(tag, _line, startCol, -1, buffer); oneStmtToken.push_back(keyword); } else { // It is identifier Token keyword(ID, _line, startCol, -1, buffer); oneStmtToken.push_back(keyword); } } else if ( type == DELIMIT ) { // Convert char to string to be stored in Token stringstream ss; ss << current; string cur; ss >> cur; Token delimit(current, _line, _col, -1, cur); oneStmtToken.push_back(delimit); } else if ( type == REGEXSTART ) {
void PNMFileUtils::extractToken(ifstream &inputStream, char *token, int maxSize) { int count = 0; char ch; // skip whitespace and comments do { inputStream.read((char *)&ch, sizeof(char)); // if a comment char is found then read till the next "\n" if(ch == '#') while(ch != '\n') inputStream.read((char *)&ch, sizeof(char *)); } while(ch == ' ' || ch == '\t' || ch == '\n'); // copy data into token do { if(count >= maxSize - 1) throw runtime_error("Token too large"); token[count++] = ch; inputStream.read((char *)&ch, sizeof(char)); } while(ch != ' ' && ch != '\t' && ch != '\n' && ch != '.'); inputStream.putback(ch); token[count] = '\0'; }
void getStatements(ifstream &file) { string token,tmp; tmp=Peek(file); if (tmp=="}" || tmp==")") return; while (true) { file >> token; if (token=="}") { file.unget(); return; } if (token=="var") getVarsDeclaration(file); else { //token eh nome tmp=token; file >> token; // pega o segundo token depois do nome putback(token,file); // retorna ponteiro para o nome do file.putback(1); while (file.peek()==' '); putback(tmp,file); //retorna ponteiro para antes do token if (token=="(") getFuncCall(file); cout << endl; } expect(";",file); } }
void getVarsDeclaration(ifstream &file) { //var ja foi consumido string token; //---------------------------- file >> token; // "name?" file.putback(token.length()); // retorna "name?" if (token==";") { cout << "expected: variable identifier" <<endl; exit(0); } while (token!=";" && file.good()) { file >> token; // name file >> token; // separador ou terminador if (token!="," && token!=";") { cout << "expected: variable identifier separator or declaration terminator" <<endl; exit(0); } file.unget(); //putback the ; } }
ContractInfoRec::ContractInfoRec(ifstream &ifs, const char * const sf, int line): Record(ContractInfo, sf, line) { ifs.get(Contract, sizeof(Contract)); ContractLetter = Contract[0]; char buf2[2+1]; buf2[0] = Contract[1]; buf2[1] = Contract[2]; buf2[2] = '\0'; BasePrice = atoi(buf2); buf2[0] = Contract[3]; buf2[1] = Contract[4]; SubLevel = atoi(buf2); char c; unsigned int i = 0; do { ifs.get(c); if (i < sizeof(Text)-2) { Text[i] = c; i++; } } while (c != '\n'); if (Text[i-1] == '\n') Text[i-1] = '\0'; else Text[i] = '\0'; ifs.putback('\n'); }
bool eof(ifstream& in) { char ch; in >> ch; in.putback(ch); return !in; }
void skipspaces() { char ch; do { ch = fin.get(); } while(isspace(ch)); fin.putback(ch); }
/*VARIABLES FUNCTION Define: READS AND STORES VARIABLES*/ string VARIABLES::Define(ifstream &Input) { //DECLARE LOCAL VARIABLES string Read_Next(ifstream &Input); string str; int i; char c; const int n = 7; int delim[n] = {9,10,13,32,44,61,124};/*{'\t','\n','?CR?',' ',',','=','|'}*/ //GET VARIABLE NAME (WITHOUT LETTING Read_Next TRY TO REPLACE) str.clear(); while (Input.get(c)) { //Check for comments if(int(c)=='%') { Input.ignore(10001, '\n'); continue; } //Check for deliminators for(i=0;i<n;i++) { if(int(c)==delim[i]) { i=-1; break; } } if(i!=-1) {str += c;break;} } if(int(c)!='$') { //Not a valid variable name (return) Input.putback(c); return(Read_Next(Input)); } str = Read_Next(Input);//NOTE: this allows deliminators between '$' and varaible name str.insert(0, "$"); //FIND VARIABLE TO REDEFINE IT OR FIND UNUSED SLOT VARIABLES *var = this; while(var!=var->next) { if(str.compare(var->symb)==0) {break;} var = var->next; } //STORE SYMBOL AND VALUE var->symb = str; str = Read_Next(Input); i = int(str[0]); if( (i<43)||(i>57)||(i==44)||(i==47) ) {//Check if a number is present Log <<str<<" is not a valid expression for variable "<<var->symb<<endl; exit(0); } var->value = atof(str.c_str()); if(var==var->next) {var->next = new VARIABLES();}//Allocate memory for next variable return(Define(Input)); }
char SaltarSeparadores (ifstream& f) { char c; do { c= f.get(); } while (isspace(c)); f.putback(c); return c; }
// push the file read pointer one step backward void scanner::pushBackPointer(char ch) { if(ch=='\n') { linenum--; } fin.putback(ch); }
float getValeur(ifstream &fichier, char caractere) { float temp = 0; fichier.putback(caractere); fichier>>temp; return temp; }
void buildMap(ifstream& input, Map<string, Vector<char> >& _Map_, int& orderK) { char ch; while(input.get(ch)) { input.putback(ch); Vector<char> associatedValues; /* All the values associated with a key. */ Vector<char> rewindValues; /* Holds chars to be put back into stream. */ string newKey = ""; /* Create a new key by appending as many letters as K value. */ addToString(input, ch, newKey, rewindValues, orderK); /* Add to the key Map. */ addToKey(_Map_, associatedValues, newKey, input); /* Put back the characters into ifstream from reverse. */ for(int i=orderK-1; i>0; i--) { input.putback(rewindValues[i]); } } }
int Term2(int inp) { int result = inp; char a; testfile.get(a); if(a != EOF) { if (a == '*') result = Term2(result * Fact()); else if (a == '/') result = Term2(result / Fact()); else if (a == '+' || a == '-') testfile.putback(a); } return result; }
// this is already inside the loop E'--> +TE'|-TE'| e int Exp2(int input){ int result = input; char a; if (!fin.eof() ){ fin.get(a); //if( (a = fin.get()) != fin.eof()){ // just another way i could have written this. works for my notes. if (a == '+') result = Exp2(result + Term() ); else if(a == '-') result = Exp2(result - Term() ); else if(a == ')') fin.putback(a); } return result; }
// T'--> *FT'| /FT'| e int Term2(int input){ int result = input; char a; //if( (a = fin.get()) != fin.eof() ){ // just another way i could have written this. works for my notes. if (!fin.eof() ){ fin.get(a); if (a == '*') result = Term2(result * Pwr() ); else if (a == '/') result = Term2(result / Pwr() ); else if (a == '+' || a == '-' || a == ')') // i added the ')' to close the parenthesis . it does this because when it finds it a gets put back so it knows what operation to do fin.putback(a); } return result; }
int Pwr(){ int p = Fact(); char a; if (!fin.eof() ){ fin.get(a); if (a == '^') p = pow(p, Pwr()); if (a == '+' || a == '-' || a == '*' || a == '/' || a == ')') fin.putback(a); } return p; }
Context handle_code(ifstream& inFile, ofstream& outFile) { char ch; while(inFile.get(ch)) { switch(ch) { case '/': if(!inFile.get(ch)) { outFile.put('/'); return file_end; } else { if(ch == '*') return c_comment; else if(ch == '/') return cpp_comment; else { cout << "Context = / followed by reg. text, ch = " << ch << endl; outFile << keyWord; keyIndex = 0; strncpy(keyWord,"\0", 64); outFile.put('/'); inFile.putback(ch); break; } } case '\"' : return string_literal; case '\'' : return char_literal; case '\n' : return newline; default: { keyMatch(ch, outFile); } } } return file_end; }
int CFileSystemByteArray::ReadByteArray2D( ifstream &stream, int nx, int ny, BYTE *pdata ) { string buffer; int result; while ( ReadOpenClosePar( stream ) != 0 ) { ReadString( stream, buffer ); // str if ( g_verbose > 1) { cout << "Read token <" << buffer << ">\n"; } switch( token_match( buffer, token_list, token_num ) ) { case TOKEN_YSLICE: if ( g_verbose > 1 ) { cout << "Reading Y-slice\n"; } result &= ReadByteArray1D( stream, nx, pdata ); pdata += nx; break; default: cout << "ReadByteArray2D::Unknown token <"; cout << buffer.c_str() << " >\n"; break; } ReadClosePar( stream ); // } } stream.putback( '}' ); return true; }
float lireValeur(ifstream &fichier, std::vector<float> &valeurs) { char caractere; float val; fichier.get(caractere); if(caractere == '%') { fichier.get(caractere); int nbr = (int)getValeur(fichier, caractere); if(nbr >= 0 && nbr < (int)valeurs.size()) val = (int)valeurs[nbr]; } else { fichier.putback(caractere); fichier>>val; } return val; }
/** * \brief Read single single symbol into the end of a string buffer. * \param fin The input file stream. * \param str The string buffer. */ void readsinglesymbol(ifstream& fin, string& str) { char currentchar; fin.get(currentchar); if (fin.eof()) { return; } if (currentchar == '\"') { // read a string literal do { str += currentchar; fin.get(currentchar); } while (currentchar != '\"'); str += currentchar; } else { do { str += currentchar; fin.get(currentchar); } while ((false == iswhitespace(currentchar)) && ('(' != currentchar) && (false == fin.eof())); fin.putback(currentchar); } }
// herbert: fixed TestComment void SplineGeometry2d :: TestComment ( ifstream & infile ) { bool comment = true; char ch; while ( comment == true && !infile.eof() ) { infile.get(ch); if ( ch == '#' ) { // skip comments while ( ch != '\n' && !infile.eof() ) { infile.get(ch); } } else if ( ch == '\n' ) { // skip empty lines ; } else if ( isspace(ch) ) { // skip whitespaces ; } else { // end of comment infile.putback(ch); comment = false; } } return; }
static int do_pgn(ifstream &infile, const string &book_name, bool firstFile) { ArasanVector<ChessIO::Header> hdrs; long games = 0L; ColorType side = White; while (!infile.eof() && infile.good()) { long first; side = White; ResultType last_result = UnknownResult; hdrs.removeAll(); int c; // skip to start of next header (handles cases where // comment follows end of previous game). while (infile.good() && (c = infile.get()) != EOF) { if (c=='[') { infile.putback(c); break; } } ChessIO::collect_headers(infile,hdrs,first); ++games; #ifdef _TRACE cout << "game " << games << endl; #endif int move_num = 0; // process a game Board board; int var = 0; const int MAX_VAR = 20; Variation varStack[MAX_VAR]; varStack[var++] = Variation(board,0); Variation &topVar = varStack[0]; Board p1,p2; for (;;) { string num; ChessIO::Token tok = ChessIO::get_next_token(infile); if (tok.type == ChessIO::Eof) break; else if (tok.type == ChessIO::OpenVar) { if (var >= MAX_VAR-1) { cerr << "error: variation nesting limit reached" << endl; continue; } // New variation is starting. Its start position is the current // board, -1 halfmove Move lastMove = varStack[var-1].lastMove(); board.undoMove(lastMove,varStack[var-1].moves[ varStack[var-1].moves.size()-1].state); Variation newVar(board,move_num); // start of variation varStack[var++] = newVar; varStack[var-1] = varStack[var-1]; // new top of stack side = OppositeColor(side); } else if (var && tok.type == ChessIO::CloseVar) { const Variation &branchPoint = varStack[var-1]; processVar(branchPoint,firstFile); if (var >= 2) { Variation &parent = varStack[var-2]; // minimax child variation evals back to parent if (parent.save.sideToMove() == branchPoint.save.sideToMove()) { // maximize parent.eval = (PositionEval)Util::Max( (int)parent.eval, (int)branchPoint.eval); } else { // minimize parent.eval = (PositionEval)Util::Min( (int)parent.eval, (int)branchPoint.eval); } } // reset board to start of variation board = branchPoint.save; --var; // now reapply last move from the parent variation // (main line move) ASSERT(var); Move mainLine = varStack[var-1].moves[varStack[var-1].moves.size()\ -1].move; board.doMove(mainLine); side = board.sideToMove(); } else if (tok.type == ChessIO::NAG) { // applies to the previous move or line auto it = moveEvals.find(tok.val); if (it != moveEvals.end()) { // get last move and set its eval varStack[var-1].moves[varStack[var-1].moves.size()-1].moveEval = (*it).second; } //check for position eval auto it2 = positionEvals.find(tok.val); if (it2 != positionEvals.end()) { // associate it with the current variation varStack[var-1].eval = (PositionEval)((*it2).second); } } else if (tok.type == ChessIO::Comment) { string comment(tok.val); if (comment.length() > 0 && comment[0] == '{') { string::iterator it = comment.begin()+1; // remove initial brace & leading spaces after it while (it != comment.end() && #ifdef __CYGWIN__ (((unsigned char)(*it))<=0x7f) && #else isascii(*it) && #endif isspace(*it)) it++; comment = string(it,comment.end()); } if (comment.length() >= 8 && comment.substr(0,7) == "weight:") { stringstream s(tok.val.substr(8)); int num; s >> num; if (s.good()) { // get last move and set its recommendation if (num >=0 && num <=100) { if (varStack[var-1].moves.size()) { varStack[var-1].moves[varStack[var-1].moves.size()-1].rec = num; } else { cerr << "warning: misplaced weight comment, ignored" << endl; } } else { cerr << "Warning: invalid move weight: " << num << ", ignored" << endl; } } } else if (comment.length()>=3) { if (comment.substr(0,7) == "1/2-1/2" || comment.substr(0,3) == "\xBD-\xBD") { varStack[var-1].result = DrawResult; } else if (comment.substr(0,3) == "1-0") { varStack[var-1].result = White_Win; } else if (comment.substr(0,3) == "0-1") { varStack[var-1].result = Black_Win; } } }
int CFileSysEntryDataAsciiIO::ReadFile( ifstream &stream ) { int result; string tokenid; int entry_tokenid; string entry_keyword; string entry_classname; string entry_type; string entry_readfunc; string entry_readbasicfunc; string entry_writebasicfunc; string entry_writefunc; string entry_suffix; string entry_readbinaryfunc; string entry_writebinaryfunc; result = true; if ( g_verbose ) { cout << "Reading CFileSysEntryDataAsciiIO" << endl; } while ( g_filesysascii.ReadOpenClosePar( stream ) != 0 ) { g_filesysascii.ReadString( stream, tokenid ); if ( g_verbose > 1 ) { cout << "Read Token = <" << tokenid << ">\n"; } switch( token_match( tokenid, token_list, token_num ) ) { case TOKEN_TOKENID: g_filesysascii.ReadInteger( stream, entry_tokenid ); m_tokenid = entry_tokenid; if ( g_verbose ) { cout << "Read <tokenid> = <" << entry_tokenid << ">" << endl; } break; case TOKEN_KEYWORD: g_filesysascii.ReadQuotedString( stream, entry_keyword ); m_keyword = entry_keyword; if ( g_verbose ) { cout << "Read <keyword> = <" << entry_keyword << ">" << endl; } break; case TOKEN_CLASSNAME: g_filesysascii.ReadQuotedString( stream, entry_classname ); m_classname = entry_classname; if ( g_verbose ) { cout << "Read <classname> = <" << entry_classname << ">" << endl; } break; case TOKEN_TYPE: g_filesysascii.ReadQuotedString( stream, entry_type ); m_type = entry_type; if ( g_verbose ) { cout << "Read <type> = <" << entry_type << ">" << endl; } break; case TOKEN_READFUNC: g_filesysascii.ReadQuotedString( stream, entry_readfunc ); m_readfunc = entry_readfunc; if ( g_verbose ) { cout << "Read <readfunc> = <" << entry_readfunc << ">" << endl; } break; case TOKEN_READBASICFUNC: g_filesysascii.ReadQuotedString( stream, entry_readbasicfunc ); m_readbasicfunc = entry_readbasicfunc; if ( g_verbose ) { cout << "Read <readbasicfunc> = <" << entry_readbasicfunc << ">" << endl; } break; case TOKEN_WRITEBASICFUNC: g_filesysascii.ReadQuotedString( stream, entry_writebasicfunc ); m_writebasicfunc = entry_writebasicfunc; if ( g_verbose ) { cout << "Read <writebasicfunc> = <" << entry_writebasicfunc << ">" << endl; } break; case TOKEN_WRITEFUNC: g_filesysascii.ReadQuotedString( stream, entry_writefunc ); m_writefunc = entry_writefunc; if ( g_verbose ) { cout << "Read <writefunc> = <" << entry_writefunc << ">" << endl; } break; case TOKEN_SUFFIX: g_filesysascii.ReadQuotedString( stream, entry_suffix ); m_suffix = entry_suffix; if ( g_verbose ) { cout << "Read <suffix> = <" << entry_suffix << ">" << endl; } break; case TOKEN_READBINARYFUNC: g_filesysascii.ReadQuotedString( stream, entry_readbinaryfunc ); m_readbinaryfunc = entry_readbinaryfunc; if ( g_verbose ) { cout << "Read <readbinaryfunc> = <" << entry_readbinaryfunc << ">" << endl; } break; case TOKEN_WRITEBINARYFUNC: g_filesysascii.ReadQuotedString( stream, entry_writebinaryfunc ); m_writebinaryfunc = entry_writebinaryfunc; if ( g_verbose ) { cout << "Read <writebinaryfunc> = <" << entry_writebinaryfunc << ">" << endl; } break; default: cout << "CFileSysEntryIO::Unknown token <" << tokenid << ">\n"; break; } g_filesysascii.ReadClosePar( stream ); } stream.putback( '}' ); if ( g_verbose ) { cout << "Reading complete." << endl << endl; } return( result ); }
int CFractalParamsListDataAsciiIO::ReadFile( ifstream &stream ) { int result; string tokenid; int entry_listnum; CFractalParameters * entry_fractal; result = true; #ifdef DEBUG cout << "CFractalParamsListDataAsciiIO::ReadFile\n"; #endif if ( g_verbose ) { cout << "Reading CFractalParamsListDataAsciiIO" << endl; } while ( g_filesysascii.ReadOpenClosePar( stream ) != 0 ) { g_filesysascii.ReadString( stream, tokenid ); #ifdef DEBUG cout << "Token = " << tokenid << endl; #endif if ( g_verbose > 1 ) { cout << "Read Token = <" << tokenid << ">\n"; } switch( token_match( tokenid, token_list, token_num ) ) { case TOKEN_LISTNUM: g_filesysascii.ReadInteger( stream, entry_listnum ); reserve( entry_listnum ); #ifdef DEBUG cout << "Read <listnum> = <" << entry_listnum << ">" << endl; #endif if ( g_verbose ) { cout << "Read <listnum> = <" << entry_listnum << ">" << endl; } break; case TOKEN_GROUP: entry_fractal = new CFractalParameters; entry_fractal->ReadFile( stream ); push_back( *entry_fractal ); #ifdef DEBUG cout << "Read <fractal> = <" << &at( size()-1 ) << ">" << endl; #endif if ( g_verbose ) { cout << "Read <fractal> = <" << &at( size()-1 ) << ">" << endl; } break; default: cout << "CFractalParamsListIO::Unknown token <" << tokenid << ">\n"; break; } g_filesysascii.ReadClosePar( stream ); } stream.putback( '}' ); if ( g_verbose ) { cout << "Reading complete." << endl << endl; } return( result ); }
void ArffParser::readHeader( ifstream& in, NameMap& classMap, vector<NameMap>& enumMaps, NameMap& attributeNameMap, vector<RawData::eAttributeType>& attributeTypes ) { bool isData = false; string tmpStr; string tmpAttrType; locale labelsLocale = locale(locale(), new nor_utils::white_spaces("{,}")); while ( !isData ) { switch ( getNextTokenType(in) ) { case TT_DATA: isData = true; break; case TT_COMMENT: getline(in, tmpStr); // ignore line break; case TT_RELATION: in >> _headerFileName; break; case TT_ATTRIBUTE: in >> tmpStr; if ( nor_utils::cmp_nocase(tmpStr, "class") ) { // It's a class!! char firstChar = 0; while ( isspace(firstChar = in.get()) && !in.eof() ); in.putback(firstChar); getline(in, tmpStr); stringstream ss(tmpStr); ss.imbue(labelsLocale); // read the classes for (;;) { ss >> tmpStr; if ( ss.eof() ) break; tmpStr = nor_utils::trim(tmpStr); if (!tmpStr.empty()) classMap.addName(tmpStr); } in.putback( '\n' ); } else if ( nor_utils::cmp_nocase(tmpStr.substr(0,5), "class") ) { classMap.addName(tmpStr.substr(5)); _hasAttributeClassForm = true; } else { NameMap enumMap; in >> tmpAttrType; if ( nor_utils::cmp_nocase(tmpAttrType, "numeric") || nor_utils::cmp_nocase(tmpAttrType, "real") || nor_utils::cmp_nocase(tmpAttrType, "integer") ) { attributeNameMap.addName(tmpStr); attributeTypes.push_back(RawData::ATTRIBUTE_NUMERIC); } else if ( nor_utils::cmp_nocase(tmpAttrType, "string") ) { if (attributeNameMap.getNumNames() == 0) _hasName = true; else { cerr << "ERROR: One can specify the name of an example only as the first attribute, otherwise string types are not supported!!" << endl; exit(1); } } else { // enum attributeTypes // For the time being the enumeration cannot contain spaces, we should // correct it. if (tmpAttrType[0] == '{') { attributeNameMap.addName(tmpStr); attributeTypes.push_back(RawData::ATTRIBUTE_ENUM); stringstream ss(tmpAttrType); ss.imbue(labelsLocale); for (;;) { ss >> tmpAttrType; if ( ss.eof() ) break; tmpAttrType = nor_utils::trim(tmpAttrType); if (!tmpAttrType.empty()) enumMap.addName(tmpAttrType); } } else { cerr << "ERROR: Unknown attribute type " << tmpAttrType[0] << endl; exit(1); } }
float ChargerEquation(ifstream &fichier, const Caracteristique &caract, int level, char priorite, bool *continuer) { float valeur = 0; char caractere; do { fichier.get(caractere); if (caractere == '+') { if(priorite == '+') { valeur += ChargerEquation(fichier, caract, level, '+', continuer); if(!*continuer) return valeur; else *continuer = false; } else { fichier.putback(caractere); *continuer = true; return valeur; } } else if (caractere == '-') { if(priorite == '+') { valeur -= ChargerEquation(fichier, caract, level, '-', continuer); if(!*continuer) return valeur; else *continuer = false; } else { fichier.putback(caractere); *continuer = true; return valeur; } } else if (caractere == '*') { if(priorite == '+' || priorite == '-') { valeur *= ChargerEquation(fichier, caract, level, '*', continuer); if(!*continuer) return valeur; else *continuer = false; } else { fichier.putback(caractere); *continuer = true; return valeur; } } else if (caractere == '/') { if(priorite == '+' || priorite == '-') { valeur /= ChargerEquation(fichier, caract, level, '*', continuer); if(!*continuer) return valeur; else *continuer = false; } else { fichier.putback(caractere); *continuer = true; return valeur; } } else if (caractere == '^') { if( priorite == '*' || priorite == '+' || priorite == '-') { float temp = ChargerEquation(fichier, caract, level, '^', continuer); float buf = valeur; for(int i = 1 ; i < (int)temp ; ++i ) valeur *= buf; if(temp == 0) valeur = 1; if(!*continuer) return valeur; else *continuer = false; } else { fichier.putback(caractere); *continuer = true; return valeur; } } else if (caractere == 'l') valeur = level; else if (caractere == 'i') { int no = 0; fichier>>no; if(no >=0 && no < 4) valeur = caract.degatsMin[no]; } else if (caractere == 'a') { int no = 0; fichier>>no; if(no >=0 && no < 4) valeur = caract.degatsMax[no]; }
// Get the next token from the input stream. bool gettoken(string &tok) { char ch; char ch2; static bool trackIndent = true; tok = ""; ch = fin.get(); // Check for EOF and return false if EOF // is found. if(!fin) return false; // Read whitespace. if(isspace(ch)) { while(isspace(ch)) { tok += ch; // Reset indent counter with each new line. if(ch == '\n') { indent = ""; trackIndent = true; } else if(trackIndent) indent += ch; ch = fin.get(); } fin.putback(ch); return true; } // Stop tracking indentation after encountering // first non-whitespace character on a line. trackIndent = false; // Read an identifier or keyword. if(isalpha(ch) || ch=='_') { while(isalpha(ch) || isdigit(ch) || ch=='_') { tok += ch; ch = fin.get(); } fin.putback(ch); return true; } // Read a number. if(isdigit(ch)) { while(isdigit(ch) || ch=='.' || tolower(ch) == 'e' || ch == '-' || ch =='+') { tok += ch; ch = fin.get(); } fin.putback(ch); return true; } // Check for \" if(ch == '\\') { ch2 = fin.get(); if(ch2 == '"') { tok += ch; tok += ch2; ch = fin.get(); } else fin.putback(ch2); } // Check for '"' if(ch == '\'') { ch2 = fin.get(); if(ch2 == '"') { tok += ch; tok += ch2; return true; } else fin.putback(ch2); } // Check for begin comment symbols. if(ch == '/') { tok += ch; ch = fin.get(); if(ch == '/' || ch == '*') { tok += ch; } else fin.putback(ch); return true; } // Check for end comment symbols. if(ch == '*') { tok += ch; ch = fin.get(); if(ch == '/') { tok += ch; } else fin.putback(ch); return true; } tok += ch; return true; }
/** * \brief Read, parse, evaluate, and print the expression one by one from * the input stream. * * \param fin The input file stream. */ void readfile(ifstream& fin) { string sexp; bool isstartsexp = false; int inumleftparenthesis = 0; // check whether to read the end while (!fin.eof()) { // read char by char char currentchar; fin.get(currentchar); if (fin.eof()) { break; } // skip some white space before new s-expression occurs if ((true == iswhitespace(currentchar))&&(false == isstartsexp)) { continue; } // run across a new s-expression if ((false == isstartsexp)&&(false == iswhitespace(currentchar))) { // check whether single symbol if ('(' != currentchar) { // read a single symbol fin.putback(currentchar); readsinglesymbol(fin, sexp); // call function parse_eval_print(sexp); sexp.clear(); } else { // start new expression isstartsexp = true; // read left parenthesis sexp += currentchar; inumleftparenthesis = 1; } } else { // in the process of reading the current s-expression if (true == isstartsexp) { if (true == iswhitespace(currentchar)) { // append a blankspace //sexp += ' '; sexp += currentchar; } else { // append current character sexp += currentchar; // count left parenthesis if ('(' == currentchar) { inumleftparenthesis ++; } if (')' == currentchar) { inumleftparenthesis --; // check whether current s-expression ends if (0 == inumleftparenthesis) { // current s-expression ends isstartsexp = false; // call functions parse_eval_print(sexp); sexp.clear(); } } } } } } }
void readLabel(ifstream &cfg_ptr, const char *label) { register int i; register unsigned char c = '\0'; char line[100]; bool stop = false; // Strip off blank lines and comment lines. // int get() -> Extracts a character from the stream and returns its value (casted to an integer). while (!stop && ((i = cfg_ptr.get()) != EOF)) { c = (unsigned char) i; if ((c == '\n') || (c == COMMENT_CHAR)) { while ((c != '\n') && ((i = cfg_ptr.get()) != EOF)) { c = (unsigned char) i; } } else { stop = true; } } if (!stop) { cerr << "Error: file EOF encountered before " << label << " found. - 1 \n"; exit(4); } cfg_ptr.putback(c); //rewind (put character back) // Decrements the internal get pointer by one, // and c becomes the character to be read // at that position by the next input operation. // Read in the strings until label is found or EOF encountered. // The skipws flag (skip whitespaces) is set in standard streams on initialization while ((cfg_ptr >> line)) // will automatically skip all the spaces and enters { cout<<"[unprocessed line] "<<line<<endl; if ((line[0] != COMMENT_CHAR) && (line[0] != '\n')) { if (strncmp(line, label, strlen(label)) == 0) { printf("found %s \n", label); return; } } c = '\0'; // if '\n' or '#' are not the first character of a line while ((c != '\n') && ((i = cfg_ptr.get()) != EOF)) { c = (unsigned char) i; } } cerr << "Error: file EOF encountered before " << label << " found. - 2\n"; exit(4); }
void SplineGeometry2d :: LoadData ( ifstream & infile ) { enum { D = 2 }; int nump, numseg, leftdom, rightdom; Point<D> x; int hi1, hi2, hi3; double hd; char buf[50], ch; materials.SetSize(0); maxh.SetSize(0); infile >> elto0; TestComment ( infile ); infile >> nump; for (int i = 0; i < nump; i++) { TestComment ( infile ); for(int j=0; j<D; j++) infile >> x(j); infile >> hd; Flags flags; ch = 'a'; // infile >> ch; do { infile.get (ch); } while (isspace(ch) && ch != '\n'); while (ch == '-') { char flag[100]; flag[0]='-'; infile >> (flag+1); flags.SetCommandLineFlag (flag); ch = 'a'; do { infile.get (ch); } while (isspace(ch) && ch != '\n'); } if (infile.good()) infile.putback (ch); geompoints.Append (GeomPoint<D>(x, hd)); geompoints.Last().hpref = flags.GetDefineFlag ("hpref"); geompoints.Last().hmax = 1e99; } // PrintMessage (3, nump, " points loaded"); TestComment ( infile ); infile >> numseg; bcnames.SetSize(numseg); for ( int i = 0; i < numseg; i++ ) bcnames[i] = 0; // "default"; SplineSeg<D> * spline = 0; // PrintMessage (3, numseg, " segments loaded"); for (int i = 0; i < numseg; i++) { TestComment ( infile ); infile >> leftdom >> rightdom; infile >> buf; // type of spline segement if (strcmp (buf, "2") == 0) { // a line infile >> hi1 >> hi2; spline = new LineSeg<D>(geompoints[hi1-1], geompoints[hi2-1]); } else if (strcmp (buf, "3") == 0)