[英]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.