【发布时间】: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;
}
【问题讨论】:
-
运行时大小数组 == 使用
std::vector -
如果这是一个家庭任务,您可能可以使用预定义常量
const int MAX_BOOKS = 1000并检查输入的n是否小于MAX_BOOKS。所以你可以将你的数组声明为struct books b[MAX_BOOKS],但迭代它直到n