简体   繁体   中英

Input an amount of elements of a structure from keyboard (not having a constant value) c++

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM