簡體   English   中英

從鍵盤輸入結構元素的數量(沒有常數值) c++

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

我需要輸入將有多少作者/行但是具有恆定值是不可能的

換句話說,這

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

你想要的是一個可以在運行時調整大小的數組,稱為動態數組。 struct books b[n]; 是一個 static 數組,這意味着它在編譯時被解析。 所以你要找的是std::vector<books> 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.

您不能在同一個 scope 中重新定義。 因此,請確保 scope 中的所有變量都有不同的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM