-1

昨日、みんなが家族と楽しい時間を過ごせたことを願っています!郊外にいる家族を訪ねているときに、締め切りが迫っているいくつかのプロジェクトに着手しようと思いました。そのうちの 1 つは、構造体の配列を使用してデータを保存および変更する C で記述されたコードを C++ に変換することです。オブジェクトの配列を使用するコード。私は最近 C プログラミングの構文に慣れてきましたが、これが C++ での最初のプロジェクトになります。クラスが構造体に非常に似ていることは理解していますが、構文とアクセス指定子の概念について混乱しています。以下は、私のオリジナルの C コードと、変更のリストです。この種の作業のための優れたソース/チュートリアルを含む、開始方法に関する提案は大歓迎です。よろしくお願いします!

変更:

  1. クラス内のすべてのデータをプライベートとして宣言します。
  2. プログラムが動作するために必要なすべての機能を提供するメソッド (クラス関数) を提供します。特に、クラスのコンストラクター メソッドを宣言します。
  3. プログラムに必要なメソッドに加えて、クラス内の各プライベート データ メンバーに対してアクセス (\get") およびミューテーター (\set") 関数を記述します。

私のコード:

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>

//Function Prototypes
void insertFirstName(struct structureName[], char[], int);
void insertLastName(struct structureName[], char[], int);
void insertHomeNumber(struct structureName[], char[], int);
void insertCellNumber(struct structureName[], char[], int);
void printPhoneBook(struct structureName[], int);
int deleteFriend(struct structureName[], char[], int);
void showFriend(struct structureName[], char[], int);
void saveFile(FILE*, struct structureName[], int);
int loadFile(FILE*, struct structureName[]);

//Structure Declaration
typedef struct structureName{
   char *fName;  //member for First Name
   char *lName;  //member for Last Name
   char *hPhone; //member for Home Phone
   char *cPhone; //member for Cell Phone
} pbFriend;

int main(){

   int x = 0;
   int flag = 0; //returned in delete function to account for empty phonebook
   int entryCount = 0;//variable for count of entries
   int menuChoice = 0; //variable for switch statement
   int count = 0; //counter keeps track of entry numbers 
   char name[100] = {'\0'}; //place holder for entries
   pbFriend phoneBook[1000] = {'\0'}; //create instance
   char fileSave = '\0'; //variable for selection on file save query
   char fileLoad = '\0'; //variable for selection on file load query
   FILE *pbData; //file pointer

   do{
      //load file to phone book query
      printf("Welcome! Would you like to load a file into the phonebook? (y/n): ");
      scanf("%c",&fileLoad);
      getchar();

      if(fileLoad=='y'||fileLoad=='Y'){
         count = loadFile(pbData,phoneBook);
         printf("Success! File loaded!\n");
         entryCount = count;
      } //end if

      else{
         if(fileLoad!='n'&&fileLoad!='N'){
            printf("Invalid selection.\n");
         } //end if
      } //end else
   }while( fileLoad!='y'&&fileLoad!='Y'&&fileLoad!='n'&&fileLoad!='N');  //end do while

   do{
      //display menu                 
      printf("\nPhone Book Application\n");
      printf("1) Add friend\n");
      printf("2) Delete friend\n");
      printf("3) Show a friend\n");
      printf("4) Show phone book\n");
      printf("5) Quit\n");
      printf("What do you want to do?: ");
      scanf("%d",&menuChoice);
      getchar();
      switch(menuChoice){

      case 1:  //add friend case
         printf("\nFirst name: ");  //insert first name
         scanf("%s",name);
         getchar();
         //allocate memory
         phoneBook[count].fName = (char*)malloc(100*sizeof(char));

         //memory failed to allocate
         if(phoneBook[count].fName == NULL){
            printf("ERROR! Out of memory!");
         }//end if

         //memory allocated
         else{
            insertFirstName(phoneBook, name, count);   
         }//end else

         printf("Last name: "); //insert last name
         scanf("%s",name);
         getchar();

         //allocate memory
         phoneBook[count].lName = (char*)malloc(100*sizeof(char));

         //memory failed to allocate
         if(phoneBook[count].lName == NULL){
            printf("ERROR! Out of memory!");
         }//end if

         //memory allocated
         else{
            insertLastName(phoneBook, name, count);   
         }//end else

         printf("Phone number (home): "); //insert home number
         scanf("%s",name);
         getchar();

         //allocate memory
         phoneBook[count].hPhone = (char*)malloc(100*sizeof(char));

         //memory failed to allocate
         if(phoneBook[count].hPhone == NULL){
            printf("ERROR! Out of memory!");
         }//end if


         //memory allocated
         else{
            insertHomeNumber(phoneBook, name, count);   
         }//end else

         printf("Phone number (cell): "); //insert cell number
         scanf("%s",name);
         getchar();

         //allocate memory
         phoneBook[count].cPhone = (char*)malloc(100*sizeof(char));

         //memory failed to allocate
         if(phoneBook[count].cPhone == NULL){
            printf("ERROR! Out of memory!");
         }//end if

         //memory allocated
         else{
            insertCellNumber(phoneBook, name, count);   
         }//end else

         printf("Entry added to phone book!\n");
         printf("\n");
         count++;
         entryCount++;
         break;

      case 2:  //delete friend case
         printf("\nPlease provide a last name for entry deletion: ");
         scanf("%s",&name);
         getchar();
         strcat(name," "); //white space for string values
         flag = deleteFriend(phoneBook, name, count);

         //successful deletion
         if(flag == 1){
            printf("The entry has been deleted from the phonebook.\n");
            entryCount--;
         }//end if

         //no deletion
         else{
            printf("No deletion has been made.\n");
         } 
         printf("\n");
         break;

      case 3:  //show friend case
         printf("\n");
         printf("Please provide a last name: ");
         scanf("%s",&name);
         getchar();
         strcat(name," ");
         showFriend(phoneBook, name, count);
         printf("\n");
         break;

      case 4:  //show phone book case
         printf("\n");
         //empty phonebook
         if(entryCount == 0){
            printf("The phonebook is empty.\n");
         }//end if
         else{
            printPhoneBook(phoneBook, count);
         }//end else
         printf("\n");
         break;

      case 5:  //quit case
         do{
            printf("\nWould you like to save the phonebook to a file? (y/n): ");
            scanf("%c",&fileSave);
            getchar();

            switch(fileSave){
            case 'y': case 'Y': //save case
               saveFile(pbData,phoneBook,count);
               printf("Success! File saved!");
               break;       

            case 'n': case 'N': //exit without saving case 
               printf("Good bye!\n");
               break;

            default: //invalid case
               printf("Invalid selection.\n");
               break;
            } //end switch
         }while(fileSave!='y'&&fileSave!='Y'&&fileSave!='n'&&fileSave!='N'); //end do while
         break;

      default: //invalid case
         printf("Invalid menu choice.\n\n");
         break;
      }//end switch statement
   }while(menuChoice != 5); //end do while loop

   getch();
   return 0;
}//end main

//Function Definitions
//function to insert first name
void insertFirstName(pbFriend phoneBook[], char name[], int count){
   strcpy(phoneBook[count].fName, name);
   strcat(phoneBook[count].fName," ");  
}

//function to insert last name
void insertLastName(pbFriend phoneBook[], char name[], int count){
   strcpy(phoneBook[count].lName, name);
   strcat(phoneBook[count].lName," ");
}

//function to insert home phone number
void insertHomeNumber(pbFriend phoneBook[], char name[], int count){
   strcpy(phoneBook[count].hPhone, name);
   strcat(phoneBook[count].hPhone," ");
}

//function to insert cell phone number
void insertCellNumber(pbFriend phoneBook[], char name[], int count){
   strcpy(phoneBook[count].cPhone, name);
   strcat(phoneBook[count].cPhone," ");
}

//function to delete entry
int deleteFriend(pbFriend phoneBook[], char name[], int count){
   int x;
   int foundFlag = 0; //foundFlag for seeing if query is in structure
   char nullStr[30] = {'\0'}; //NULL string
   char name2[30] = {'\0'}; //string to store first name query
   //get first name to prevent multiple deletions due to same last name
   printf("Please provide the first name of the entry to be deleted: ");
   scanf("%s", &name2);
   getchar();
   strcat(name2," ");
   for(x=0;x<count;x++){
      if((strcmp(phoneBook[x].lName,name)==0)&&(strcmp(phoneBook[x].fName,name2)==0)){
         foundFlag = 1; //entry found, proceed with delete
         //free previously allocated memory
         free(phoneBook[x].fName);
         free(phoneBook[x].lName);
         free(phoneBook[x].hPhone);
         free(phoneBook[x].cPhone);
         //set free strings to NULL
         strcpy((phoneBook[x].fName), nullStr);
         strcpy((phoneBook[x].lName), nullStr);
         strcpy((phoneBook[x].hPhone), nullStr);
         strcpy((phoneBook[x].cPhone), nullStr);
      }//end if
   }//end for
   //entry not found
   if(foundFlag == 0){ 
      printf("\nSorry, there is nobody with that name in the phone book.\n");
   }//end if
   return foundFlag;
}//end function

//function to search entries by last name
void showFriend(pbFriend phoneBook[], char name[], int count){
   int x;
   int foundFlag = 0; //foundFlag for seeing if query is in structure
   printf("\n");
   for(x=0;x<count;x++){
      if(strcmp((phoneBook[x].lName), name) == 0){
         foundFlag = 1; //entry found, proceed with display
         printf("%s",phoneBook[x].fName);
         printf("%s",phoneBook[x].lName);
         printf("%s(home) ",phoneBook[x].hPhone);
         printf("%s(cell)",phoneBook[x].cPhone);
         printf("\n");
      }//end if   
   }//end for
   //entry not found
   if(foundFlag == 0){
      printf("Sorry, there is nobody with that name in the phone book.\n");
   }//end if                               
}//end function

//function to print phone book contents
void printPhoneBook(pbFriend phoneBook[], int count){
   int x;
   for(x=0;x<count;x++){
      //check to avoid NULL strings, which have been deleted
      if(strlen(phoneBook[x].fName) > 0){ 
         printf("%s", phoneBook[x].fName);
         printf("%s", phoneBook[x].lName);
         printf("%s(home) ", phoneBook[x].hPhone);
         printf("%s(cell)", phoneBook[x].cPhone);
         printf("\n");
      }//end if
   }//end for
}//end function

//function to save to a file
void saveFile(FILE *pbData, pbFriend phoneBook[], int count){
   char fileName[100] = {'\0'}; //string to store desired name to save file as
   int x = 0; //counter variable
   printf("Please enter the file name: ");
   scanf("%s",fileName);
   getchar();
   //open file
   pbData = fopen(fileName,"w");
   //file open fail case
   if(pbData == NULL){
      printf("ERROR! File not saved!\n");
      perror("The following error occurred"); //specifies i/o error
      getchar();
      exit(EXIT_FAILURE); //exit program with error
   } //end if
   //file open success case
   else{
      //write to file   
      for(x=0;x<count;x++){
         fprintf(pbData, "%s", phoneBook[x].fName);
         fprintf(pbData, "%s", phoneBook[x].lName);
         fprintf(pbData, "%s", phoneBook[x].hPhone);
         fprintf(pbData, "%s", phoneBook[x].cPhone);
      } //end for
      fclose(pbData);
   } //end else
}// end function

//function to load a file into the phone book
int loadFile(FILE *pbData, pbFriend phoneBook[]){
   char fileName[100] = {'\0'}; //variable to store name of file to load
   int count = 0; //counter variable
   char tabulaRasa[30] = {'\0'}; /*NULL string to clear garbage data from the
                                 last loop of the feof() condition when loading 
                                 files*/
   printf("Please enter the name of the file you wish to load: ");
   scanf("%s",fileName);
   getchar();
   //open file
   pbData = fopen(fileName,"r");
   //file open fail case
   if(pbData == NULL){
      printf("ERROR! Unable to load file!\n");
      perror("The following error occurred"); //specifies i/o error
      getchar();
      exit(EXIT_FAILURE); //exit program with error
   } //end nested if
   //file open success case
   else{
      //allocate memory to store data from a file
      while(!feof(pbData)){
         phoneBook[count].fName = (char*)malloc(100*sizeof(char));
         if(phoneBook[count].fName == NULL){
            printf("ERROR! Out of memory!");
         } //end double nested if
         phoneBook[count].lName = (char*)malloc(100*sizeof(char));
         if(phoneBook[count].lName == NULL){
            printf("ERROR! Out of memory!");
         } //end double nested if
         phoneBook[count].hPhone = (char*)malloc(100*sizeof(char));
         if(phoneBook[count].hPhone == NULL){
            printf("ERROR! Out of memory!");
         } //end double nested if
         phoneBook[count].cPhone = (char*)malloc(100*sizeof(char));
         if(phoneBook[count].cPhone == NULL){
            printf("ERROR! Out of memory!");
         } //end double nested if
         //load from file
         fscanf(pbData,"%s",phoneBook[count].fName);
         strcat(phoneBook[count].fName," "); 
         fscanf(pbData,"%s",phoneBook[count].lName);                         
         strcat(phoneBook[count].lName," ");
         fscanf(pbData,"%s",phoneBook[count].hPhone);
         strcat(phoneBook[count].hPhone," ");
         fscanf(pbData,"%s",phoneBook[count].cPhone);
         strcat(phoneBook[count].cPhone," ");
         count++; //show that entry/entries have been made from file
      }//end while loop
      //free memory of last entry (junk data from feof() condition)
      free(phoneBook[count-1].fName);
      free(phoneBook[count-1].lName);
      free(phoneBook[count-1].hPhone);
      free(phoneBook[count-1].cPhone);
      //set newly free strings to NULL
      strcpy((phoneBook[count-1].fName), tabulaRasa);
      strcpy((phoneBook[count-1].lName), tabulaRasa);
      strcpy((phoneBook[count-1].hPhone), tabulaRasa);
      strcpy((phoneBook[count-1].cPhone), tabulaRasa);
      count--;
   } //end nested else
   fclose(pbData);
   return(count); //show that phone book is not empty
} //end if
4

1 に答える 1

3

目の前のタスクを開始するための優れた方法は、C++ 入門ページの項目のいくつかを確認することです。

于 2012-11-23T20:56:44.243 に答える