0

I need to input how many authors/rows there will be but with constant value it's impossible

In other words, this

const int n = 2;
struct books b[n];
int i;

must be changed to something like this

int n;
cin >> n;
struct books b[n];

I think the solution has something to do with dynamic allocation but I don't know exactly how to realize it

Full code:

#include <cstring>
#include <iostream>

using namespace std;

struct books
{
    string name;
    string nameOfBook;
    string publisher;
    int year;
};

int main() {

    const int n = 2;
    struct books b[n];
    int i;

    int n;
    cin >> n;
    struct books b[n];

    for (i = 0; i < n; i++)
    {
        cout << "Author " << i + 1 << endl;

        cout << "Enter name" << endl;
        cin >> b[i].name;

        cout << "Enter a name of a book" << endl;
        cin >> b[i].nameOfBook;

        cout << "Enter a publisher" << endl;
        cin >> b[i].publisher;

        cout << "Enter the year of publishing" << endl;
        cin >> b[i].year;
        cout << endl;
    }

    cout << "Author \t" << "Name of an author: \t" << "Name of a book: \t" << "Name of a publisher: \t" << "The year of publishing: \t" << endl;

    for (i = 0; i < n; i++)
    {
        cout << i + 1 << "\t" << b[i].name << "\t\t\t" << b[i].nameOfBook << "\t\t\t" << b[i].publisher << "\t\t\t" << b[i].year << endl;
    }

    return 0;
}
ovvvol
  • 25
  • 1
  • 5
  • 7
    Run time size array == use `std::vector` – NathanOliver Jan 20 '21 at 15:29
  • 1
    If this is a home task, you probably can use predefined constant like `const int MAX_BOOKS = 1000` and check whether entered `n` is less than `MAX_BOOKS`. So you can declare your array as `struct books b[MAX_BOOKS]` but iterate over it up to `n` – user2807083 Jan 20 '21 at 15:34
  • Possible duplicate of https://stackoverflow.com/questions/14139076/c-dynamic-array-of-structures and https://stackoverflow.com/questions/4506166/dynamic-array-in-c – saxbophone Jan 20 '21 at 15:34

1 Answers1

1

What you want is an array that can be resized at runtime, which is known as a dynamic array. struct books b[n]; is a static array, meaning that it is resolved at compile time. So what you are looking for is std::vector<books> b(n).

Secondly you have some variables with the same name,

const int n = 2;      // #1
struct books b[n];    // #2
int i;

int n;                // <-- Redefinition of #1.
cin >> n;             
struct books b[n];    // <-- Redefinition of #2.

You cannot have redefinitions in the same scope. So make sure that all your variables in a scope has different names.

D-RAJ
  • 3,263
  • 2
  • 6
  • 24