// Michael J. Fischer // CPSC 223b, Spring 2008 // Problem set 4: Flex demo // This program demonstrates how to use Flex and manage memory properly #include #include #include #include "util.h" #include "flex.h" int fill( Flex cart ); void process( Flex cart ); int main( void ) { // create a new Flex data structure called "cart" Flex cart = newFlex(); // put some things into the cart while (fill( cart ) != EOF) process( cart ); // done with cart, so clean up freeFlex( cart ); // announce termination printf( "Goodbye!\n" ); } // ----------------------------------------------------- int fill( Flex cart ){ // put some things into the cart char buf[100]; String newStr; printf( "Please type a sentence " "(single period or ^D ends session): " ); for (;;) { if (scanf( "%99s", buf) == EOF || (strcmp( buf, "." )==0 && lenFlex( cart )==0) ) { return EOF; } // copy contents of buf to new String newStr = safe_malloc( strlen( buf )+1 ); strcpy( newStr, buf ); insertFlex( cart, newStr ); if ( buf[strlen(buf)-1] == '.' ) break; } return 0; } // ----------------------------------------------------- void process( Flex cart ) { // sort cart sortFlex( cart ); // get its length and contents int len = lenFlex( cart ); String* wordList = extractFlex( cart ); // ExtractFlex passes ownership of wordList // and the strings to which its elements point. // We are responsible for freeing them when we're // done processing them. // print out our word list for (int k=0; k