-1

ユーザーは、私が集めなければならない本を配列に入力します。2冊目に入ると、1冊目がえりせんなのですが、その理由を教えていただけませんか?BOOK aux をグローバルに定義しました...

収集できない理由を理解するのを手伝ってもらえますか

#define   stop __asm nop
#include "book.h"
#include <iostream>
#include <cstdio>

using namespace std;

int counter = 0;
BOOK aux [1];

void print_catalogue()
{

}

void print_book(BOOK aBook)
{
    cout << endl;
    cout <<aBook.Autor<<", "<<aBook.Title<<", "<<aBook.Year<<", "<<aBook.PageCount<<", "<<aBook.Cost<<endl; 
}


void new_book()
{
    BOOK temp;
    system("cls");
    cin.getline (temp.Autor, 20);
    cout <<"ENTERING NEW BOOK: " << endl <<endl;
    cout <<"Input the author: ";
    cin.getline (temp.Autor, 20);
    cout  <<"Input the title: ";
    cin.getline (temp.Title, 50);
    cout  <<"Input the year of publishing: ";
    cin >>  temp.Year;
    cout  <<"Input the number of pages: ";
    cin >>  temp.PageCount;
    cout  <<"Input the cost: ";
    cin >>  temp.Cost;
    cout << endl;   

    counter++;

    BOOK * pn = new BOOK [counter];
    if (counter > 0)
    {
        memcpy(pn, aux, counter * sizeof(BOOK));    
    }
    pn[counter - 1] = temp;

    BOOK * aux = new BOOK[counter];
    memcpy(aux,pn, counter * sizeof(BOOK));

    delete[] pn;

    for (int i = 0; i < counter; i++)
    {
        print_book(aux[i]);
    }   

    system("pause");
    return;
}

void delete_books()
{

}

 void write_catalogue()
 {

 }

 void read_catalogue()
 {

 }

void menu()
{
    char command;
    do
    {       
        system("cls");

        cout << "p - Print the whole catalogue."<< endl;
        cout << "n - Input a new book." << endl;
        cout << "d - Delete existing book(s)." << endl;
        cout << "w - Write the catalogue to a file." << endl;
        cout << "r - Read the catalogue from a file." << endl;
        cout << "Input a new command: ";
        cin >> command;


        cout << endl << endl;
        switch (command) 
        {
            case 'p': print_catalogue(); break;
            case 'n': new_book(); break;
            case 'd': delete_books(); break;
            case 'w': write_catalogue(); break;
            case 'r': read_catalogue(); break;
            case 'q': return;
            default : 
                {
                    cout << "Please, enter a correct command." << endl;
                    system("pause");
                }
        }

    } while(true);
}

void main()
{
    menu();

}
4

1 に答える 1

2

グローバル aux は、1 つの BOOK (aux[0]) への定数ポインターであり、それ以上ではありません。複数のBOOK hierをコピーすることはできません。グローバルを非表示にして、ローカル AUX を再定義します。あなたがそこに置いたのは、関数 new_book() が返された後の「リーク」です。

std::string とコンテナーを使用し、ポインターとグローバル変数を悪用しないでください。

于 2013-01-08T13:34:49.090 に答える