#include #include #include #include #include #include #include #include using namespace std; // // Purpose: Problem 3, Homework 1 using string instead of char* // Usage: hw1-3-str // Note: ctrl-c to terminate // const int MAX_LINE = 100; const int MAX_NWORDS = 10; const char *WHITE = " \t\n"; // white space characters #define is_defined(x) ((value.find(x) == value.end()) ? 0 : 1) static inline void ShowPrompt(void) { printf(">> "); } int getTokens(char *cmnd, char *word[], const char *delim); struct ltstr { bool operator()(const string s1, const string s2) const { return s1 < s2; } }; // --| the main man |-- int main (int argc, char *argv[]) { char cmnd[MAX_LINE]; char *word[MAX_NWORDS]; int nwords; string wordstr[2]; map value; // string instead of char* ShowPrompt(); while ( cin.getline(cmnd, MAX_LINE) ) { nwords = getTokens(cmnd, word, WHITE); if (nwords != 2) { printf("*** Gurk!!! nwords not equal to 2. Try again.\n"); ShowPrompt(); continue; } for (int i=0; i<2; i++) wordstr[i] = word[i]; // convert to string //XXX printf("word[0:1] = <%s, %s>\n", wordstr[0].c_str(), wordstr[1].c_str()); if ( wordstr[0] == "show" ) { //XXX printf( "got show\n"); printf("%s %s\n", wordstr[1].c_str(), value[wordstr[1]].c_str()); } else { map::iterator p; printf( "got variable %s with value %s\n", wordstr[0].c_str(), wordstr[1].c_str() ); value[word[0]] = word[1]; printf( "\t> Show new table:\n" ); // extra code for (p = value.begin(); p != value.end(); p++) { printf ("\t> key = %s, value = %s\n", (p->first).c_str(), (p->second).c_str()); } printf("\n"); } ShowPrompt(); } return 0; } // --| get tokens (words) |-- int getTokens(char *cmnd, char *word[], const char *delim) { int nwords = 0; char *p = cmnd; char *token; while ((token=strtok(p,delim)) != NULL) { word[nwords] = token; //XXX printf( "\tword[%d] = %s\n", nwords, token ); nwords++; p = NULL; } word[nwords] = NULL; return nwords; }