// Phil Ottewell's STL Course - http://www.pottsoft.com/home/stl/stl.htmlx // // Example 7.1 © Phil Ottewell 1997 // // Purpose: // Use map to implement a simple token database // ANSI C Headers #include // C++ and STL Headers #include #include #include #include #ifdef _WIN32 using namespace std; #endif #ifdef _WIN32 // We know basic_string generates long names # pragma warning(disable:4786) #endif int main( int argc, char *argv[] ) { size_t ip, lnum; fstream fs; string filename, line, token, value; map< string, double > token_data; // End of declarations ... if ( argc > 1) { filename = *argv[0]; } else { filename = "tokens.dat"; } // Open the file for reading fs.open( filename.c_str(), ios::in ); // Read each line and parse it lnum = 0; while ( fs.good() ) { getline( fs, line ); if ( fs.good() ) { // Parse out the tokens and values ++lnum; ip = line.find_first_of("="); if ( ip == line.npos ) { cerr << "Invalid Line " << lnum << ": " << line << endl; continue; } token = line.substr(0,ip); ip = token.find(" "); if ( ip != token.npos ) token = token.substr(0,ip); value = line.substr(ip+1); ip = value.find_first_of("0123456789.+-"); if ( ip != value.npos ) { // Store token and value value = value.substr(ip); token_data[token] = atof( value.c_str() ); } else { cerr << "Bad value at line " << lnum << ": " << value << endl; } } // Junk everything except alphanumerics, brackets and operators /* ip = 0; while ( ip < line.length() ) { nxc = line.at(ip); if ( isspace(nxc) || (!isalnum(nxc) && !precedence(nxc) && nxc != '(' && nxc != ')') ) { line.erase(ip,1); } else { ++ip; } } */ } if ( !lnum ) { cerr << "Invalid or empty file: " << filename << endl; } else { for ( map< string, double >::iterator im = token_data.begin(); im != token_data.end(); ++im ) cout << "\"" << im->first << "\" = " << im->second << endl; cout << "Enter token name: "; getline( cin, token ); // Use the find function so we can spot a "miss" im = token_data.find( token ); if ( im != token_data.end() ) { cout << " Found \"" << im->first << "\" = " << im->second << endl; } else { cout << "token_data.find(...) shows no token matches \"" << token << "\"" << endl; cout << "Lookup using token_data[\"" << token << "\"] would have given " << token_data[token] << endl; } } return( EXIT_SUCCESS ); }