【问题标题】:Input an amount of elements of a structure from keyboard (not having a constant value) c++从键盘输入结构元素的数量(没有常数值)c ++
【发布时间】:2021-01-20 15:28:27
【问题描述】:

我需要输入将有多少作者/行,但使用恒定值是不可能的

换句话说,这个

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

必须改成这样的

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

我认为解决方案与动态分配有关,但我不知道具体如何实现

完整代码:

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

【问题讨论】:

标签: c++ struct constants


【解决方案1】:

你想要的是一个可以在运行时调整大小的数组,称为动态数组。 struct books b[n]; 是一个静态数组,意味着它是在编译时解析的。所以你要找的是std::vector&lt;books&gt; b(n)

其次,你有一些同名的变量,

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.

您不能在同一范围内进行重新定义。因此,请确保作用域中的所有变量都具有不同的名称。

【讨论】:

    猜你喜欢
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 2019-03-08
    相关资源
    最近更新 更多