How to create a user-defined amount of objects?

Asked

Viewed 26 times

0

I am creating a Bookshop and at the time of registering a new book, the user must say the amount of books that will be registered, but I am not able to do it, I can only create a preset amount of object.

Here in the code I tried to create an array, but it requires that it be a constant prevented the user from defining the amount that will be created.

void AddNewBook() {
    system("CLS");

    int amountBooks;

    std::cout << "How many books will be added? ";
    std::cin >> amountBooks;

    if (amountBooks < 1) {
         Error("No book will be added.");
         Options(Choice());
    }
    else {
        Book books[amountBooks];
    }
}

I wonder if there is a way to create the amount of objects that the user needs dynamically?

I beg your pardon if my doubt is not clear.

  • I think this can help you: https://stackoverflow.com/questions/44678457/dynamic-objects-in-c/44678941#:~:text=If%20you%20write%20A%20*%20a,A%20and%20not%20an%20array. and also: https://answall.com/questions/87980/forms

1 answer

0


Cannot create statically allocated array using a non-constant size (not known at compile time).

Correct means of declaring an array:

char array[5];

const size_t amount = 10;
char array[amount];

#define amount 15;
char array[amount];

static constexpr size_t amount = 20;
char array[amount];

To create an array that has a dynamic size, just use one of the Std library templates, the vector:

#include <vector>
std::vector<Book> books;
Book book;
books.push_back(book);

Is used push_back() to add elements to the vector and operator [] to access them just like in an array. It is not necessary to specify a size at boot time, but to decrease the amount of allocations (and increase performance), you can use reserve() to preset the size of vector.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.