#include #include #include #include #include #include using namespace std; // // Purpose: Problem 3, Homework 1 // Usage: hw1-3 // Note: ctrl-c to terminate // const int MAX_LINE = 100; const int MAX_NWORDS = 10; const char *WHITE = " \t\n"; // white space characters static inline void ShowPrompt(void) { printf(">> "); } int getTokens(char *cmnd, char *word[], const char *delim); struct ltstr { bool operator()(const char *s1, const char *s2) const { return strcmp(s1, s2) < 0; } }; // --| the main man |-- int main (int argc, char *argv[]) { char cmnd[MAX_LINE]; char *word[MAX_NWORDS]; int nwords; map value; // C++ programmers may prefer // string instead of char* ShowPrompt(); while (fgets(cmnd, MAX_LINE, stdin) != NULL) { nwords = getTokens(cmnd, word, WHITE); if (nwords != 2) { printf("*** Gurk!!! nwords not equal to 2. Try again.\n"); ShowPrompt(); continue; } //XXX printf("word[0:1] = <%s, %s>\n", word[0], word[1]); if (strcmp(word[0], "show") == 0) { //XXX printf( "got show\n"); printf("%s %s\n", word[1], value[word[1]]); } else { map::iterator p; char *pp = value[strdup(word[0])]; //XXX printf( "got variable %s with value %s\n", word[0], word[1] ); if (pp != NULL) { // name already in table free(value[word[0]]); value[word[0]] = strdup(word[1]); } else { // new name value[strdup(word[0])] = strdup(word[1]); } printf( "\t> Show new table:\n" ); // extra code to show new table for (p = value.begin(); p != value.end(); p++) { printf ("\t> key = %s, value = %s\n", p->first, p->second); } 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; }