简体   繁体   English

从键盘输入结构元素的数量(没有常数值) c++

[英]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.是一个 static 数组,这意味着它在编译时被解析。 So what you are looking for is std::vector<books> b(n) .所以你要找的是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.您不能在同一个 scope 中重新定义。 So make sure that all your variables in a scope has different names.因此,请确保 scope 中的所有变量都有不同的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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