C++数组结构

标签 c++ arrays struct

我用c++做了一个图书存储程序。这是一个循环超过 3 次的程序,因此用户可以输入 3 本书,但现在我希望用户选择用户想要输入的书籍数量,但我不知道该怎么做。这会很有帮助,这是我的代码

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct Book{
    string name;
    int release;
}Issue[3];

int main(){
    //local variable
    int i;
    string release_dte;
    //interface
    cout << "Welcome to Book Storage CPP" << endl;
    //for handler
    for (i = 0; i < 3; i++){
        cout << "Book: ";
        getline(cin, Issue[i].name);
        cout << "Release Date: ";
        getline(cin, release_dte);
        Issue[i].release = atoi(release_dte.c);
    }
    cout << "These are your books" << endl;
    for ( i = 0; i < 3; i++){
        cout << "Book: " << Issue[i].name << " Release Date: " << Issue[i].release << endl;
    }
    system("pause");
    return 0;
}

最佳答案

最好的方法是使用 std::vector。例如

#include <vector>
//...

struct Book{
    string name;
    int release;
};

int main()
{
   size_t issue_number;

   std::cout << "Enter number of books: ";
   std::cin >> issue_number;

   std::vector<Book> Issue( issue_number );
//...    

否则你应该自己动态分配数组。例如

Book *Issue = new Book[issue_number];

在程序结束时你需要释放分配的内存

delete []Issue;

关于C++数组结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21516001/

相关文章:

java - Java 中复制数组的这些方法有什么区别?

Python:比较列表和创建数组

c++ - 确定用作参数的结构数组的大小

C++字节流

c++ - MySQL C++ 连接器 : what is the correct way to use SetBlob() to set multiple blob data in a query?

c++ - Release模式工作正常但 Debug模式给出未处理的异常 - 使用 Octave DLL

php - 访问多维数组中的数据

c - 为什么我会收到此错误 : "data definition has no type or storage class"?

c++ - 大型矩阵的矩阵库?

C++ While 循环中的 vector 拆分有什么问题