-1
어제 모두 가족들과 즐거운 시간을 보내길 바랍니다! 시내에있는 가족을 방문하는 동안 곧 마감일이 오는 일부 프로젝트를 시작하겠다고 생각했습니다. 그 중 하나는 C로 작성된 코드를 변환하고 구조체의 배열을 사용하여 데이터를 저장 및 수정하고 C++로 변환하는 것입니다. 객체의 배열을 사용하는 코드. 최근에 나는 C 프로그래밍 문법에 익숙해졌지만, 이것은 C++의 저의 첫 프로젝트입니다. 나는 클래스가 구조체와 매우 흡사하다는 것을 알고 있지만 액세스 지정자의 개념은 물론 구문에 대해서 혼란 스럽다. 아래는 원래의 C 코드와 변경 목록입니다. 이런 종류의 작업을위한 훌륭한 소스/튜토리얼을 비롯하여 시작하는 방법에 대한 제안은 크게 감사하겠습니다. 미리 검토해 주셔서 감사합니다!C 구조체를 C++ 클래스로 변환
수선 :
- 선언 비공개로 클래스의 모든 데이터;
- 은 프로그램에 필요한 모든 기능 (예 : )을 제공하는 메서드 (클래스 함수)를 제공합니다. 특히, 클래스 에 대한 생성자 메서드를 선언하십시오.
- 프로그램에 필요한 메소드 외에도 클래스의 각 개인 데이터 멤버에 대해 액세스 (\ get ") 및 mutator (\ 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
가족과 함께하는 추수 감사절을 즐기면서 코드에 들여 쓰기를 할 수 있었으면 좋겠습니다. –
'// end if','// else else', 심각하게? – rightfold
C++ 클래스와 구조체의 유일한 차이점은 structs 멤버는 기본적으로 public이고 클래스 멤버는 기본적으로 private입니다. 또한 C++에서는 "typedef"가 필요 없습니다. –