ActionBase::ResultE Switch::render(Action *action)
{
    ActionBase::ResultE  returnValue = ActionBase::Continue;

    DrawActionBase  *da          = dynamic_cast<DrawActionBase *>(action);

    if((getChoice() >= 0                          ) && 
       (UInt32(getChoice()) < action->getNNodes()))
    {
        da->useNodeList();

        if(da->isVisible(action->getNode(getChoice())))
        {
            da->addNode(action->getNode(getChoice()));
        }
    }
    else if(getChoice() == ALL)
    {
        if(da->selectVisibles() == 0)
        {
            returnValue = ActionBase::Skip;
        }
    }
    else
    {
        returnValue = ActionBase::Skip;
    }

    return returnValue;
}
void ramPresetTab::guiEvent(ofxUIEventArgs &e) {
	int choice = getChoice(e, cameraPresetRadio);
	if(choice != -1) {
		int indices[] = {0, 1, 5};
		int choice = getChoice(cameraPresetRadio);
		ramCameraManager::instance().rollbackDefaultCameraSetting(indices[choice]);
	}
}
Example #3
0
int main(void){
	double balance = 0, wager = 0;
	int choice = 0;

	printGameRules();
	balance = getBankBalance();
	
	//Display game menu and allow user to continually choose options until they quit
	while(choice != 4){
		displayGameMenu();
		choice = getChoice();
		switch (choice){
			case 1: 
				printf("Current bank balance: $%.2lf\n", balance);
				break;
			case 2: 
				balance = addMoney(balance);
				printf("You now have $%.2lf in the bank\n", balance);
				break;
			case 3:
				balance = playRound(balance);
				break;
			case 4:
				break;
			default:
				printf("\nMenu choice is invalid, Please choose a number between 1 and 4\n"); //Validates menu choice
				break;
		}

	}


	return 0;
}
Example #4
0
//
// sets
//
void Choice::setChoice(int choice)
{
	m_choice = choice;
	if (m_choice < 0) m_choice = 0;
	if (m_choice >= (int)m_choices.size()) m_choice = 0;
	changeCaption(getChoice());
}
Example #5
0
int main(){	
	// create queue
	int queue[QUEUE_SIZE]={0};
	int rear = 0;
	int front = 0;
	int choice;
	while(1){
		showInitile();
		choice = getChoice();
		switch(choice){
			case 1:
				displayQueue(queue);
				break;
			case 2:
				Enqueue(queue, &rear, &front);
				break;
			case 3:
				delqueue(queue, &rear, &front);
				break;
			case 4:
				system("CLS");
				break;
			default:
				printf("你壞壞\n");
				break;
		}
	}
	system("pause");
	return 0;
}
Example #6
0
void deleteAllContacts (int *iLen, int *iCap) {
    // If no entries are stored, the request is declined and the user is informed.
    if (*iLen > 0) {

        // The user chooses whether to confirm the decision to delete all contacts.
        char cConfirmChoice = '\0';
        printf ("\nDo you wish to delete all contacts?");
        printf ("\n\t(1) Yes");
        printf ("\n\t(2) No\n");
        getChoice (&cConfirmChoice, '2');

        /* If the user chooses to continue deleting all contacts, the following
         * procedure is executed: the length and capacity counters of the PhoneBook
         * are both set to zero.
         */
        if (cConfirmChoice == '1') {
            *iLen = 0;
            *iCap = 0;
            printf ("All contacts have been deleted.\n");
        }
        else
            printf ("All contacts have been retained.\n");
    }
    else
        printf ("There are no contacts to delete.\n");
}
Example #7
0
/* ---------------------- MAZE MAIN PROGRAM --------------------------------*/
void main() {
int x1;
int y1;
int r,cl;
int isX;
int choice;

  progname();
  _setcursortype(_NOCURSOR);
  textmode(64);
  textbackground(BLUE);
  for(;;){
       choiceID = 1;
       display_atik_atik_Menu();
       choice = getChoice();
       switch(choice){
	  case 1:
		playMaze();
		break;
	  case 2:
		viewGameDevelopers();
		break;
	  case 3:
		exit(0);
		break;

       }
  }

}
Example #8
0
int profileManager(int choice){
	int fileFlag,option;
	FILE *pProfiles;
	fileFlag=checkFileExists("profiles.txt");
	switch(choice){
		case 1:
			if(fileFlag){
				pProfiles=fopen("profiles.txt","r");
				printProfiles(pProfiles);
				option = getChoice();
				if(tolower(option) == 'n'){	
					addProfile();
				}else if(tolower(option) == 'q'){
					fclose(pProfiles);
					return 0;
				}else if(tolower(option) == 'd'){
					
				}else{

				}

				fclose(pProfiles);
				return option-'0';
			}else{
				return makeProfileFile();

			}
		case 2:
			if(fileFlag){
				
			}else{

			}
	}
}
void luProjPanel::OnObjTypeChanged(wxCommandEvent& event)
{
	wxChoice* choice = getChoice();
	int sel = choice->GetCurrentSelection();
	int type = (int)choice->GetClientData(sel);
	//gkPrintf("%d %d", sel, type);

}
int DIALOG_LAYERS_SETUP::getLayerTypeIndex( LAYER_NUM aLayer )
{
    wxChoice*  ctl =  getChoice( aLayer );

    int ret = ctl->GetCurrentSelection();   // indices must have same sequence as LAYER_T

    return ret;
}
Example #11
0
//
// Pour quand on clic dessus, le child saura quoi faire
//
void Choice::onRightClic()
{
	dksPlaySound(m_sfxClic, -1, 200);
	
	// On loop les choix
	m_choice--;
	if (m_choice < 0) m_choice = (int)m_choices.size() - 1;
	changeCaption(getChoice());
}
Example #12
0
//
// Pour quand on clic dessus, le child saura quoi faire
//
void Choice::onClic()
{
	dksPlaySound(m_sfxClic, -1, 200);
	
	// On loop les choix
	m_choice++;
	if (m_choice >= (int)m_choices.size()) m_choice = 0;
	changeCaption(getChoice());
}
Example #13
0
void DIALOG_LAYERS_SETUP::showLayerTypes()
{
    for( LAYER_NUM copperLayer = FIRST_COPPER_LAYER;
             copperLayer <= LAST_COPPER_LAYER; ++copperLayer )
    {
        wxChoice* ctl = getChoice( copperLayer );
        ctl->SetSelection( m_Pcb->GetLayerType( copperLayer ) );
    }
}
Example #14
0
task main()
{
	if(getChoice("What pitch?", "Low", "High") == 0)
	{
		PlayImmediateTone(440, 100);
	}else{
		PlayTone(880, 100);
	}
	wait1Msec(1000);
}
void DIALOG_LAYERS_SETUP::showLayerTypes()
{
    for( LSEQ seq = LSET::AllCuMask().Seq();  seq;  ++seq )
    {
        LAYER_ID cu_layer = *seq;

        wxChoice* ctl = getChoice( cu_layer );
        ctl->SetSelection( m_Pcb->GetLayerType( cu_layer ) );
    }
}
Example #16
0
int main(){

	int choice = 0;

	do{
		choice = getChoice("Please select an action", menu);
		printf("You have chose: %c\n", choice);
	}while(choice != 'q');

	exit(0);
}
ActionBase::ResultE Switch::intersect(Action *action)
{
    ActionBase::ResultE  returnValue = ActionBase::Continue;
    IntersectAction     *ia          = dynamic_cast<IntersectAction *>(action);

    if((getChoice()         >= 0              ) && 
       (UInt32(getChoice()) <  ia->getNNodes())   )
    {
        ia->useNodeList(                        );
        ia->addNode    (ia->getNode(getChoice()));
    }
    else if(getChoice() == ALL)
    {
        returnValue = ActionBase::Continue;
    }
    else
    {
        returnValue = ActionBase::Skip;
    }

    return returnValue;
}
void ramPresetTab::guiEvent(ofxUIEventArgs &e)
{
	// camera
	int choice = getChoice(e, preset_cam_radio);
	if(choice != -1)
	{
		int indices[] = {0, 1, 5};
		int choice = getChoice(preset_cam_radio);
		ramCameraManager::instance().rollbackDefaultCameraSetting(indices[choice]);
	}
	
	// preset scenes
	const string name = e.widget->getName();
	
	if      (name == "Line") callPreset(0);
	else if (name == "Hasty Chase") callPreset(1);
	else if (name == "HC + Stamp") callPreset(2);
	else if (name == "HC + Stamp + Natto") callPreset(3);
	else if (name == "HC + Future") callPreset(4);
	else if (name == "Line + Future") callPreset(5);
	else if (name == "Particles + Future") callPreset(6);
	else if (name == "Particles") callPreset(7);}
Example #19
0
int  main()
{
  try
  {
    const string  stageFilename  =  getFilename( stage_ );
    const string  riderFilename  =  getFilename( rider_ );


    //
    // Setup the race data analyzer
    //
    RaceAnalyzer  raceData( stageFilename, riderFilename );

    bool  done  =  false;


    //
    // Loop until the userwants to quite
    //
    while( ! done )
    {
      //
      // Get a process the user's menu choice
      //
      switch( getChoice() )
      {
        case  menuDisplaySummary_  :  displaySummary( raceData );
                                      break;

        case  menuDisplayRiders_   :  displayRiderData( raceData );
                                      break;

        case  menuDisplayTeams_    :  displayTeamData( raceData );
                                      break;

        case  menuQuit_            :  done  =  true;
                                      break;

        default                    :  assert(true);
      }
    }

  }
  catch(...)
  {
    system("pause");
    return  EXIT_FAILURE;
  }

  return  EXIT_SUCCESS;
}
Example #20
0
/*
Main menu interface
*/
void run(FILE *file) {
    int choice = 0;
    
    while (1) {
        displayMenu();
        choice = getChoice();
        if (choice == -2) {
            exit(0);
        } else if (choice == -1) {
            append(file);
        } else if (choice == 0) {
            displayAll(file);
        } else if (choice > 0) {
            modifyRecord(choice, file);
        } else {
            printf("\n%s\n", "Invalid choice, try again!");
        }
    } 
}
Example #21
0
/* ===== process =====
    This function presents the user with the menu.
    Pre     hash, list, tree
    Post    nothing
 */
void process (HASH *hash, D_LIST *list, BST_TREE *tree)
{
    //	Local Definitions
	char choice;
	CAR car;
    
    //	Statements
	do
    {
	    choice = getChoice ();
        
	    switch (choice)
        {
	        case 'P': printHash(hash);
                printLinkedList(list);
                printManager(tree);
                break;
			case 'R': printIndentedBST(tree);
                break;
			case 'E': printData(hash);
                break;
	        case 'S': searchByHash(hash, list);
                break;
			case 'T': searchByDList(list);
                break;
			case 'I': car = addNewNode();
                insert(hash,car);
                insertDNode(list, car);
                insertTree(tree,car);
                break;
			case 'D': deleteCar(list, hash, tree);
                break;
			case 'W': writeToFile(list);
                break;
	        case 'Q': break;
        } // switch
    } while (choice != 'Q');
	return;
}	// process
main()
{
	Student students[10],s;
	char sname[10];
	int n,i,choice;
	do
	{
		choice = getChoice();
		switch(choice)
		{
			case 1:
			cout<<"\n Enter how many students records:";
			cin>>n;
			for(i = 0;i < n;i ++)
			{
				cout<<"\n Enter details of student "<<i+1;
				students[i].getData();
			}
			break;

			case 2:
			cout<<"\n Enter which student ditails want to display:";
			cin>>sname;
			cout<<"\n Roll No \tName\tMarks1\tMarks2\tMarks3\n";
			s.displayDetails(students,sname,n);
			break;

			case 3:
			cout<<"\n Student information. ";
			cout<<"\n Roll No  \tName\tMarks1\tMarks2\tMarks3\n";
			s.displayDetails(students,n);
			break;
		}
	}while(choice != 4);
	getch();
	return 0;
}
Example #23
0
void loadContactsFromFile (ContactType **pList, int *iLen, int *iCap)
{
    char cConfirmChoice = '1';

    /* If there are contacts in memory, the user is asked whether to proceed
     * with loading from the file, which will overwrite the stored contacts.
     */
    if (*iLen > 0) {
        printf ("\nCurrently stored contacts will be lost. Continue?");
        printf ("\n\t(1) Yes");
        printf ("\n\t(2) No\n");
        getChoice (&cConfirmChoice, '2');
    }

    /* If there were no contacts stored in memory, or if the user decided
     * to overwrite them, then the procedure continues.  Otherwise, loading
     * the contacts is aborted and the contacts stored in memory are retained.
     */
    if (cConfirmChoice == '1') {
        const char *cDefaultFileName = "contacts.dat";
        char cFileChoice = '\0';
        char cFileName[51] = "";
        FILE *pRead = NULL;

        // The user chooses whether to specify a path or accept the default.
        printf ("\nWhere are the contacts saved?");
        printf ("\n\t(1) Specify file-name path.");
        printf ("\n\t(2) Use default file-name path.\n");
        getChoice (&cFileChoice, '2');

        // If the user chose to specify a path:
        if (cFileChoice == '1') {
            char *cInputString = NULL;
            int iMaxLength = 1000;
            while (cInputString == NULL && iMaxLength > 0) {
                cInputString = (char *) calloc(iMaxLength + 1, sizeof(char));
                iMaxLength -= 10;
            }

            if (cInputString != NULL) {
                // Get the user's path choice and copy it to cFileName.
                printf ("File-name (and location): ");
                scanf ("%s", cInputString);
                strncpy (cFileName, cInputString, 50);
            }
            else {
                // If cInputString was not allocated memory, terminate the program.
                perror("Out of memory");
                exit(EXIT_FAILURE);
            }
            // Allocated memory is freed from cInputString.
            free(cInputString);
        }
        else
            // If the user chose to accept the default path:
            strncpy (cFileName, cDefaultFileName, 50);

        // Open the file for reading.
        pRead = fopen(cFileName, "r");

        /* If the file was opened successfully, begin loading data.  Otherwise
         * issue an error.
         */
        if (pRead != NULL) {
            /* Read the first field in the data file as an integer.  This will be
             * the number of records which will be stored.  Since struct array
             * may not hold enough space for this many records, this value must
             * be used to allocate space.
             */
            int iNewCap = 0;
            fscanf (pRead, "%d", &iNewCap);

            ContactType *pNewList = NULL;
            pNewList = (ContactType *) realloc(*pList, iNewCap * sizeof(ContactType));

            /* If the allocation was successful, then the struct array is moved to the
             * the new pointer, and the new capacity is recorded.
             */
            if (pNewList != NULL) {
                *pList = pNewList;
                *iCap = iNewCap;
            }
            else {
                // If the allocation was unsuccesful, the program ends.
                perror ("Out of memory");
                exit(EXIT_FAILURE);
            }

            /* Now, the data can be read into the array of ContactType.  The integer
             * value at the beginning of the file determined how many entries will be
             * read.
             */
            int i;
            for (i = 0; i < *iCap; i++)
                fscanf (pRead, "%s%s%s", (*pList + i)->cFirstName, (*pList + i)->cLastName, (*pList + i)->cPhoneNumber);

            /* The length of the list of entries is recorded as *iCap, the number of
             * entries saved.
             */
            *iLen = *iCap;
            // Close the file and notify the user that the contacts have been loaded.
            fclose (pRead);
            printf ("Contacts loaded from %s.\n", cFileName);
        }
        else {
            // If the file could not be opened, notify the user.
            printf ("Invalid file-name or location.\n");
            printf ("Currently stored contacts are retained.\n");
        }
    }
    else
        // If the user chose not to overwrite stored contacts, notify her and continue execution.
        printf ("Currently stored contacts are retained.\n");
}
Example #24
0
User *chooseUser(){
  int unumber;
  showUsers();
  unumber = getChoice();
  return &users[(unumber - 1)];
}
int main(){
	FILE *fp, *ft; 		
	char another, choice;
	
	/** structure to employee */
	struct emp{
		char name[50];
		int age;
		float salary;
	} e;
    
    char empname[50]; 

    long int recsize; 

    /** 
	*	Opening file if exits or creating new file 
    */
    fp = fopen(FILE_NAME,"rb+");
    
    if(fp == NULL)
    {
        fp = fopen(FILE_NAME,"wb+");
        if(fp == NULL)
        {
            printf("Cannot open the file");
            exit(1);
        }
    }

    recsize = sizeof(e);

   
    
    while(1)
    {
    	choice = getChoice();
        
        switch(choice)
        {
        case '1':  // Add Record
            system("cls");
            fseek(fp,0,SEEK_END); 
            another = 'y';
            while(another == 'y')  
            {
                printf("\nEnter name: ");
                scanf("%s",e.name);
                printf("\nEnter age: ");
                scanf("%d", &e.age);
                printf("\nEnter basic salary: ");
                scanf("%f", &e.salary);

                fwrite(&e,recsize,1,fp); 

                printf("\nAdd another record(y/n) ");
                fflush(stdin);
                another = getche();
            }
            break;
        case '2': // List Record
            system("cls");
            rewind(fp); 
            while(fread(&e,recsize,1,fp)==1)  
            {
                printf("\n%s %d %.2f",e.name,e.age,e.salary); 
            }
            getch();
            break;

        case '3':  // Modify Record 
            system("cls");
            another = 'y';
            while(another == 'y')
            {
                printf("Enter the employee name to modify: ");
                scanf("%s", empname);
                rewind(fp);
                while(fread(&e,recsize,1,fp)==1)
                {
                    if(strcmp(e.name,empname) == 0)
                    {
                        printf("\nEnter new name,age and basic salary: ");
                        scanf("%s%d%f",e.name,&e.age,&e.salary);
                        fseek(fp,-recsize,SEEK_CUR); 
                        fwrite(&e,recsize,1,fp);
                        break;
                    }
                }
                printf("\nModify another record(y/n)");
                fflush(stdin);
                another = getche();
            }
            break;
        case '4': // Delete Record
            system("cls");
            another = 'y';
            while(another == 'y')
            {
                printf("\nEnter name of employee to delete: ");
                scanf("%s",empname);
                ft = fopen(TEMP_FILE_NAME,"wb");  
                rewind(fp);
                while(fread(&e,recsize,1,fp) == 1)
                {
                    if(strcmp(e.name,empname) != 0)
                    {
                        fwrite(&e,recsize,1,ft);
                    }
                }
                fclose(fp);
                fclose(ft);
                remove(FILE_NAME);
                rename(TEMP_FILE_NAME,FILE_NAME);
                fp = fopen(FILE_NAME, "rb+");
                printf("Delete another record(y/n)");
                fflush(stdin);
                another = getche();
            }
            break;
        case '5': // Exit Program
            system("cls");
            moveLocation(0,5);
            fclose(fp);  
            printf("Bye././. Have a nice day");
            moveLocation(0,7);
            
            exit(0); 
        }
    }
	
	
	return 0;
}
Example #26
0
int main(int argc, char **argv){
 
  List list = LLCreate();
  Stack stack = SCreate();
  Queue queue = QCreate();
  User *usr;

  setupUsers();
  MENU_CHOICE m_choice = MAIN_MENU;
  int choice, count;
  menu();

  choice = getChoice();
  
  while(choice){
    switch(m_choice){
    case MAIN_MENU:
      switch(choice){
      case 1:
	m_choice = LL_MENU; 
	llmenu();
	break;
      case 2:
	m_choice = QUEUE_MENU;
	qmenu();
	break;
      case 3:
	m_choice = STACK_MENU;
	smenu();
	break;
      case 4:
	showUsers();
        menu();
	break;
      case 0:
	exit(0);
	break;
      default:
	m_choice = MAIN_MENU;
	menu();
      }
      break;
    case LL_MENU:
      switch(choice){
      case 1:
	printf("\n%s\n", "adding head, choose a user");
        usr = chooseUser();
        printf("%s %s\n", "You chose ", usr -> name);
        LLAddHead(usr, list);
        llmenu();
	break;
      case 2:
	printf("\n%s\n", "adding tail, choose a user");
        usr = chooseUser();
        printf("%s %s\n", "You chose", usr -> name);
        LLAddTail(usr, list);
        llmenu();
	break;
      case 3:
	printf("\n%s\n", "removing head");
        LLRemoveHead(list);
        llmenu();
	break;
      case 4:
	printf("\n%s\n", "removing tail");
        LLRemoveTail(list);
        llmenu();
	break;
      case 5:
        print(list);
        llmenu();
	break;
      case 6:
        m_choice = MAIN_MENU;
	menu();
	break;
      case 0:
	exit(0);
	break;
      default:
	m_choice = LL_MENU;
      }
      break;
    case QUEUE_MENU:
      switch(choice){
      case 1:
        printf("\n%s\n", "enqueueing, choose a user");
        usr = chooseUser();
        printf("%s %s\n", "You chose ", usr -> name);
        Qenqueue(usr, queue);
        qmenu();
	break;
      case 2:
	printf("\n%s\n", "dequeueing");
        Qdequeue(queue);
        qmenu();
	break;
      case 3:
	print(queue);
        qmenu();
	break;
      case 4:
        m_choice = MAIN_MENU;
	menu();
	break;
      case 0:
	exit(0);
	break;
      default:
	m_choice = QUEUE_MENU;
      }
      break;
    case STACK_MENU:
      switch(choice){
      case 1:
	printf("%s\n", "push");
        smenu();
	break;
      case 2:
	printf("%s\n", "pop");
        smenu();
	break;
      case 3:
	printf("%s\n", "top");
        smenu();
	break;
      case 4:
	printf("%s\n", "print");
        smenu();
	break;
      case 5:
        m_choice = MAIN_MENU;
	menu();
	break;
      case 0:
	exit(0);
	break;
      default:
	m_choice = STACK_MENU;
      }
      break;
    } 
    choice = getChoice();
  }

  return 0;   
}
Example #27
0
/* showAllContacts allows the user to sort the contacts by first or last name
 * (or choose not to sort the contacts) and then displays them all in a list.
 */
void showAllContacts (ContactType *pList, int *iLen) {
    int i;

    /* If the contact list has fewer than two entries, then sorting is trivial.
     * Therefore the sorting menu is presented only if the length of the list
     * is larger than 1.
     */
    if (*iLen > 1) {

        // cSortChoice will store the user's choice from the sorting menu.
        char cSortChoice = '\0';

        /* lContactsSwapped and TempHolder are needed for the sorting algorithm
         * (bubble-sort).  lContactsSwapped is a logical variable that indicates
         * whether two entries in the list have been exchanged in the previous
         * pass through the list. TempHolder holds an entry temporarily so that
         * it does not get unintendedly overwritten while it is being swapped.
         */
        int lContactsSwapped;
        ContactType TempHolder = {""};

        // The sorting menu is displayed and the user's choice obtained.
        printf ("\nWould you like to sort the entries?");
        printf ("\n\t(1) by Last Name");
        printf ("\n\t(2) by First Name");
        printf ("\n\t(3) Do Not Sort\n");
        getChoice (&cSortChoice, '3');

        /* The bubble-sort algorithm. On each pass through the array of ContactType
         * adjacent entries are compared, and swapped if they are out of order.
         * The process repeats if any two entries had to be swapped in the previous
         * iteration.  Once the array has been passed through without a swap, the
         * list is known to be sorted.
         */
        do {
            lContactsSwapped = 0;
            i = 0;
            while (i < *iLen - 1) {

                /* lSwapNeeded indicates whether the entry indexed by i should be
                 * exchanged with the entry in the following position. lSwapNeeded
                 * is a logical integer variable determined according to the user's
                 * choice of sorting criteria.  If the user chose not to sort the
                 * list, lSwapNeeded retains its initialized value, 0/false.
                 */
                int lSwapNeeded = 0;
                switch (cSortChoice) {
                case '1':
                    lSwapNeeded = strcmp((pList + i)->cLastName, (pList + i + 1)->cLastName) > 0;
                    break;
                case '2':
                    lSwapNeeded = strcmp((pList + i)->cFirstName, (pList + i + 1)->cFirstName) > 0;
                    break;
                }

                // If an exchange is necessary, this simple procedure accomplishes it.
                if (lSwapNeeded) {
                    TempHolder = *(pList + i);
                    *(pList + i) = *(pList + i + 1);
                    *(pList + i + 1) = TempHolder;
                    lContactsSwapped = 1;
                }
                i++;
            }
        } while (lContactsSwapped);
    }

    //  Once sorting is complete, or if sorting was not necessary, the list is printed.
    printf ("\nPhone Book Contacts (%d):", *iLen);
    for (i = 0; i < *iLen; i++)
        printf ("\n%s\t%s\t%s", (pList + i)->cFirstName, (pList + i)->cLastName, (pList + i)->cPhoneNumber);
    printf ("\n");
}
Example #28
0
void findContact (ContactType *pList, int *iLen) {
    /* The user is allowed to search for a contact only if there is at least
     * one contact stored.
     */
    if (*iLen > 0) {

        // cInputString is prepared just as above in function getChoice.
        char *cInputString = NULL;
        int iMaxLength = 1000;
        while (cInputString == NULL && iMaxLength > 0) {
            cInputString = (char *) calloc(iMaxLength + 1, sizeof(char));
            iMaxLength -= 10;
        }

        /* If cInputString was allocated memory, then the user can proceed
         * to input field data into cInputString.
         */
        if (cInputString != NULL) {
            char cSearchChoice = '\0';
            int i = 0;
            int lMatchFound = 0;

            // The user can choose which field to use as a basis for the search.
            printf ("\nHow would you like to search?");
            printf ("\n\t(1) by Last Name");
            printf ("\n\t(2) by First Name");
            printf ("\n\t(3) by Phone Number\n");
            getChoice (&cSearchChoice, '3');

            /* The user enters a field value to search for.  If the value
             * is the same as the corresponding field in a list entry, the
             * whole entry is printed.  Because this procedure uses strcmp()
             * to compare, the user's search value must match exactly,
             * including case.
             *
             * Depending on the user's choice, she may search for a particular
             * last name, first name, or phone number.  All entries with the
             * same value for the target field will be displayed.
             */
            switch (cSearchChoice) {
            case '1':
                printf ("\nLast Name: ");
                scanf ("%s", cInputString);
                while (i < *iLen) {
                    if (!strcmp((pList + i)->cLastName, cInputString)) {
                        printf ("%s\t%s\t%s\n", (pList + i)->cFirstName, (pList + i)->cLastName, (pList + i)->cPhoneNumber);
                        lMatchFound = 1;
                    }
                    i++;
                }
                break;
            case '2':
                printf ("\nFirst Name: ");
                scanf ("%s", cInputString);
                while (i < *iLen) {
                    if (!strcmp((pList + i)->cFirstName, cInputString)) {
                        printf ("%s\t%s\t%s\n", (pList + i)->cFirstName, (pList + i)->cLastName, (pList + i)->cPhoneNumber);
                        lMatchFound = 1;
                    }
                    i++;
                }
                break;
            case '3':
                printf ("\nPhone Number: ");
                scanf ("%s", cInputString);
                while (i < *iLen)  {
                    if (!strcmp((pList + i)->cPhoneNumber, cInputString)) {
                        printf ("%s\t%s\t%s\n", (pList + i)->cFirstName, (pList + i)->cLastName, (pList + i)->cPhoneNumber);
                        lMatchFound = 1;
                    }
                    i++;
                }
                break;
            }
            /* If the logical variable lMatchFound was never set to 1, then no
             * match was found, and the user is notified.
             */
            if (!lMatchFound)
                printf ("No matches were found.\n");
        }
        else {
            // If cInputString was not allocated memory, terminate the program.
            perror("Out of memory");
            exit(EXIT_FAILURE);
        }

        // Free allocated memory.
        free(cInputString);
    }
    else
        // If (*iLen == 0),
        printf ("There are no contacts to choose from.\n");
}
Example #29
0
// Main function: Program execution begins.
main()
{

    /* Phonebook points to (the first element) of an array of structures
     * of ContactType.  Each element of the array contains all the
     * information for one record: first name, last name, and phone
     * number. Integer variables iLength and iCapacity each contain
     * information about the array.  iCapacity indicates the number of
     * entries which can be stored according to current memory allocation;
     * when iCapacity = 5, then no more than 5 records can be stored.
     * iLength indicates the number of records that are currently stored.
     * (Therefore, the last element in the array is indexed by iLength - 1.)
     */
    ContactType *PhoneBook;
    int iLength = 0;
    int iCapacity = 0;

    /* PhoneBook is allocated enough memory to match its current listed
     * capacity.  Of course, here, the listed capacity is 0, so PhoneBook
     * is not assigned any memory according to the calloc function. This
     * assignment is included for form's sake, to match the free(PhoneBook)
     * statement at the end of the main() function.  Adhering to the form
     * of matching memory allocation and memory freeing will ensure careful
     * programming.
     */
    PhoneBook = (ContactType *) calloc(iCapacity, sizeof(ContactType));

    /* cUserChoice will take on the value of the user's main menu choice.
     * The following loop will continue to execute until the user chooses
     * to exit.  The constant identifier cLastChoice contains the character
     * representing the last available choice ('Exit').  If the program
     * is modified to accommodate a larger or smaller menu, this constant
     * can be changed conveniently.
     */
    char cUserChoice = '\0';
    const char cLastChoice = '9';

    do {

        // The menu is displayed and the user enters her choice.
        printMainMenu ();
        getChoice (&cUserChoice, cLastChoice);

        // The appropriate function is called.
        switch (cUserChoice) {
        case '1':
            showAllContacts (PhoneBook, &iLength);
            break;
        case '2':
            addContact (&PhoneBook, &iLength, &iCapacity);
            break;
        case '3':
            findContact (PhoneBook, &iLength);
            break;
        case '4':
            getRandomContact (PhoneBook, &iLength);
            break;
        case '5':
            deleteContact (PhoneBook, &iLength);
            break;
        case '6':
            deleteAllContacts (&iLength, &iCapacity);
            break;
        case '7':
            saveContactsToFile (PhoneBook, &iLength);
            break;
        case '8':
            loadContactsFromFile (&PhoneBook, &iLength, &iCapacity);
            break;
        }
        // The application continues until the user chooses to exit.
    } while (cUserChoice != cLastChoice);

    // Freeing allocated memory.
    free (PhoneBook);

    printf ("\nGoodbye!\n\n");
}
Example #30
0
void saveContactsToFile (ContactType *pList, int *iLen)
{
    // The function will not attempt to save contacts if none are in memory.
    if (*iLen > 0) {

        /* The constant string pointer cDefaultName stores the default file location.
         * cFileChoice stores the user's choice: whether 1) to enter a file location
         * or 2) accept the default file location. The FILE pointer pWrite will hold
         * the address of the filestream where the data will be saved.
         */
        const char *cDefaultFileName = "contacts.dat";
        char cFileChoice = '\0';
        char cFileName[51] = "";
        FILE *pWrite = NULL;

        // The user chooses whether to specify a path or accept the default.
        printf ("\nWhere do you want to save the contacts?");
        printf ("\n\t(1) Specify file-name path.");
        printf ("\n\t(2) Use default file-name path.\n");
        getChoice (&cFileChoice, '2');

        /* If the user chose to enter a file location, then she is prompted
         * for one and the input is saved as cInputString and copied to
         * cFileName.  If she chose to accept the default, then cDefaultFileName
         * is copied to cFileName.
         */
        if (cFileChoice == '1') {
            char *cInputString = NULL;
            int iMaxLength = 1000;
            while (cInputString == NULL && iMaxLength > 0) {
                cInputString = (char *) calloc(iMaxLength + 1, sizeof(char));
                iMaxLength -= 10;
            }

            if (cInputString != NULL) {
                printf ("File-name (and location): ");
                scanf ("%s", cInputString);
                strncpy (cFileName, cInputString, 50);
            }
            else {
                // If cInputString was not allocated memory, terminate the program.
                perror("Out of memory");
                exit(EXIT_FAILURE);
            }
            // Allocated memory is freed from cInputString.
            free(cInputString);
        }
        else
            strncpy (cFileName, cDefaultFileName, 50);

        // The file is opened for writing, and the filestream is saved as pWrite.
        pWrite = fopen(cFileName, "w");

        // If the file was opened successfully, we continue. Otherwise, an error is printed.
        if (pWrite != NULL) {

            // The first field of data written to the file is the number of entries.
            fprintf (pWrite, "%d\n", *iLen);

            // Now, the entries are written to the file using a for-loop.
            int i;
            for (i = 0; i < *iLen; i++)
                fprintf (pWrite, "%s\t%s\t%s\n", (pList + i)->cFirstName, (pList + i)->cLastName, (pList + i)->cPhoneNumber);

            // Finally, the file is closed, and a message is printed to the user.
            fclose (pWrite);
            printf ("Contacts saved to %s.\n", cFileName);
        }
        else
            printf ("Invalid file-name or location.\n");
    }
    // If no contacts are in memory, then an error is printed to the user and the program continues.
    else
        printf ("There are no contacts to save.\n");
}