연결리스트로 학생정보 관리 프로그램 만드는데 할당된 메모리 값이 바껴버려요..

조회수 1033회

학생관리 시스템 같은걸 만드는데

파일은 main, student.cpp, student.h 이렇게 3개 쓰고있고 학생 데이터 추가할떄 링크드리스트이용해서 구현하려고 하는데 main 문을 통해서 menu 번호 받아서 switch문 안에서 학생정보추가 하고 다시 switch문에서 확인 코드 로 해보니 값이 비워져 버려요... 스위치문 안의 함수내부에서 메모리 할당을 해서 그런걸까요 ?>

int main()
{
    List list;
    ListInit(&list);

    int menunumber = 0;


    while (1)
    {
        menuout(); cin >> menunumber; system("cls");
        switch (menunumber)
        {

        case 1:AddStudent(&list); break;
        case 2:break;
        case 3:StudentListShow(&list); break;
        case 4: break;
        case 5: return 0;
        }
    }


    return 0;
}
"Kong_Student.cpp"
#pragma once
#include "Kong_Student.h"
#include <iostream>

using namespace std;

Kong_Student::Kong_Student()
{
    //ctor
}

Kong_Student::~Kong_Student()
{
    //dtor
}

void ListInit(List *plist)
{
    //plist->head = (Kong_Student*)malloc(sizeof(Kong_Student)); //더미
    plist->head = new Kong_Student();
    plist->head->next = NULL;
    plist->numOfData = 0;

}





//////////////////////////
int comparechar(char* str1, char*str2, int num)
{
    for (int i = 0; i<num; i++)
    {
        if (*(str1 + i) != *(str2 + i))return 0;
    }
    return 1;
}
void AddStudent(List *plist)
{
    //Kong_Student* Newstudent = (Kong_Student*)malloc(sizeof(Kong_Student));
    Kong_Student* Newstudent = new Kong_Student;
    Newstudent->next = plist->head->next;
    plist->head->next = Newstudent;
    (plist->numOfData)++;
    plist->cur = plist->head->next;

    char ok[2];
    while (!comparechar(ok, "Y", 1))
    {
        int itempsex;
        char chtempsex[5];
        int tempage;
        char tempname[20];
        char tempphone[20];

        cout << "성별을 입력해주세요.(남 : 0 , 여 : 1) : ";     cin >> itempsex;
        cout << "성별을 입력해주세요. : ";                      cin >> chtempsex;
        cout << "나이을 입력해주세요. : ";                      cin >> tempage;
        cout << "휴대폰 번호를 입력해주세요.(xxx-xxxx-xxxx) :"; cin >> tempphone;
        cout << "이름을 입력해주세요. : ";                      cin >> tempname;

        cout << endl << "추가 정보 확인" << endl;
        cout << "이름\t성별\t나이\t휴대폰번호" << endl;
        cout << tempname << "\t"; if (itempsex == 0)cout << "남\t"; else cout << "여\t"; cout << tempage << "\t" << tempphone << "\t" << endl << endl;
        cout << "정보가 맞습니까 ? [Y/N] ";
        cin >> ok;

        if (comparechar(ok, "Y", 1))
        {
            Newstudent->Setname(tempname);
            Newstudent->Setage(tempage);
            Newstudent->Setisex(itempsex);
            Newstudent->Setchsex(chtempsex);
            Newstudent->Setphone(tempphone);
        }

        system("cls");
    }

}

void StudentListShow(List *plist)
{
    cout << "No\t이름\t성별\t나이\t휴대폰번호" << endl;
    cout << plist->numOfData;
    for (int i = 0; i<plist->numOfData; i++)
    {
        char* tempname = plist->cur->Getname();
        cout<<i+1<<"\t"<<tempname;
    }

}
void menuout()
{
    cout << "학생관리 시스템" << endl << "Menu" << endl << endl << "[1] 학생등록" << endl << "[2] 학생삭제" << endl << "[3] 학생리스트" << endl << "[4] 정보삭제" << endl << "[5] 종료" << endl << endl << "메뉴를 선택하여 주세요 : ";
}
#ifndef KONG_STUDENT_H
#define KONG_STUDENT_H
#pragma once
#include "stdlib.h"


class Kong_Student
{
public:
    Kong_Student();
    ~Kong_Student();

    char* Getname() { return name; }
    void Setname(char* val) { name = val; }
    int Getage() { return age; }
    void Setage(int val) { age = val; }
    int Getisex() { return isex; }
    void Setisex(int val) { isex = val; }
    char* Getchsex() { return chsex; }
    void Setchsex(char* val) { chsex = val; }
    char* Getphone() { return phone; }
    void Setphone(char* val) { phone = val; }

    Kong_Student* next;
protected:

public:
    char* name;
    int age;
    int isex;
    char* chsex;
    char* phone;
};

typedef struct _linkedLIst
{
    Kong_Student* head;
    Kong_Student* cur;
    Kong_Student* before;
    int numOfData;
}LinkedLIst;

typedef LinkedLIst List;

void ListInit(List *plist);


int comparechar(char* str1, char*str2, int num);
void AddStudent(List *plist);
void StudentListShow(List *plist);
void menuout();

#endif // KONG_STUDENT_H

1 답변

  • 수정한 부분은 체크해놓았습니다.

    Kong_Student.h

    #ifndef KONG_STUDENT_H
    #define KONG_STUDENT_H
    #pragma once
    
    #include <iostream>
    #include <cstdlib>
    #include <cstring>
    
    using namespace std;
    //헤더 수정
    
    class Kong_Student
    {
        private: // public -> private
            char name[20]; //포인터에서 배열로 수정
            char chsex[10];
            char phone[20];
            int age;
            int isex;
            Kong_Student* next;
    
        public:
            Kong_Student();
            ~Kong_Student();
    
            void Getname(char* val) { strcpy(val, name); } //strcpy사용
            void Setname(char* val) { strcpy(name, val); }
    
            void Getage(int &val) { val = age; }
            void Setage(int val) { age = val; }
    
            void Getisex(int &val) { val = isex; }
            void Setisex(int val) { isex = val; }
    
            void Getchsex(char* val) { strcpy(val, chsex); }
            void Setchsex(char* val) { strcpy(chsex, val); }
    
            void Getphone(char* val) { strcpy(val, phone); }
            void Setphone(char* val) { strcpy(phone, val); }
    
            Kong_Student* GetNext(void) { return next; }
            void SetNext(Kong_Student* val) { next = val; }
    
    };
    
    struct List // C++에서는 구조체를 typedef할 필요 없음
    {
        Kong_Student* head;
        Kong_Student* cur;
        Kong_Student* before;
        int numOfData;
    };
    
    void ListInit(List *plist);
    void AddStudent(List *plist);
    void StudentListShow(List *plist);
    void menuout();
    
    //int comparechar(char* str1, char*str2, int num); // strncmp로 대체
    
    #endif // KONG_STUDENT_H
    
    

    student.cpp

    #include "Kong_Student.h"
    
    Kong_Student::Kong_Student()
    {
        //ctor
    }
    
    Kong_Student::~Kong_Student()
    {
        //dtor
    }
    
    void ListInit(List *plist)
    {
        //plist->head = (Kong_Student*)malloc(sizeof(Kong_Student)); //더미
        plist->head = new Kong_Student();
        plist->head->SetNext(NULL); //next는 SetNext로 지정
        plist->numOfData = 0;
    }
    
    /*
    int comparechar(char* str1, char*str2, int num) // strncmp로 대체
    {
        for (int i = 0; i<num; i++)
        {
            if (*(str1 + i) != *(str2 + i))return 0;
        }
        return 1;
    }
    */
    
    void AddStudent(List *plist)
    {
        //Kong_Student* Newstudent = (Kong_Student*)malloc(sizeof(Kong_Student));
        char ok[2] = "N";
        while (!strncmp(ok, "N", 1)) // N이 입력되면 계속 정보를 입력
        {
            char chtempsex[10];
            char tempname[20];
            char tempphone[20];
            int itempsex;
            int tempage;
    
            cout << "성별을 입력해주세요.(남 : 0 , 여 : 1) : ";     cin >> itempsex;
            cout << "성별을 입력해주세요. : ";                      cin >> chtempsex;
            cout << "나이을 입력해주세요. : ";                      cin >> tempage;
            cout << "휴대폰 번호를 입력해주세요.(xxx-xxxx-xxxx) :"; cin >> tempphone;
            cout << "이름을 입력해주세요. : ";                      cin >> tempname;
    
            cout << endl << "추가 정보 확인" << endl;
            cout << "이름\t성별\t나이\t휴대폰번호" << endl;
            cout << tempname << "\t"; if (itempsex == 0)cout << "남\t"; else cout << "여\t"; cout << tempage << "\t" << tempphone << "\t" << endl << endl;
            cout << "정보가 맞습니까 ? [Y/N] ";
            cin >> ok;
    
            if (!strncmp(ok, "Y", 1)) // 정보 입력 후  Y가 입력되면 객체 생성 후 리스트에 추가
            {
                Kong_Student* Newstudent = new Kong_Student;
    
                Newstudent -> Setname(tempname);
                Newstudent -> Setage(tempage);
                Newstudent -> Setisex(itempsex);
                Newstudent -> Setchsex(chtempsex);
                Newstudent -> Setphone(tempphone);
    
                Newstudent -> SetNext(plist->head->GetNext()); //next는 GetNext로 가져옴
                plist -> head -> SetNext(Newstudent);
                (plist -> numOfData)++;
                plist -> cur = plist -> head -> GetNext();
    
                break;
            }
        }
    }
    
    void StudentListShow(List *plist)
    {
        char name[20]; //포인터에서 배열로 변경
        char gender[5];
        char phone[20];
        int age;
    
        cout << "No\t이름\t성별\t나이\t휴대폰번호" << endl;
        //cout << plist->numOfData;
        Kong_Student *st = plist->cur;
        for (int i = 0; st ; i++) //st가 NULL이면 종료
        {
            st->Getname(name);
            cout<<i+1<<"\t"<<name;
    
            st->Getchsex(gender);
            cout<<"\t"<<gender;
    
            st->Getage(age);
            cout<<"\t"<<age;
    
            st->Getphone(phone);
            cout<<"\t"<<phone << endl;
    
            st = st -> GetNext();
        }
    }
    
    void menuout()
    {
        cout << "\n학생관리 시스템" << endl << "Menu" << endl << endl << "[1] 학생등록" << endl << "[2] 학생삭제" << endl << "[3] 학생리스트" << endl << "[4] 정보삭제" << endl << "[5] 종료" << endl << endl << "메뉴를 선택하여 주세요 : ";
    }
    
    

    메인함수는 그대로이며, 문법만 수정하고 논리는 그대로입니다.

    아 그리고 system함수는 지운 상태입니다.

    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)