【发布时间】:2020-04-21 00:54:20
【问题描述】:
我是这方面的新手,并没有做太多,但我真的坚持制作一个编译时大小的数组,它是一个类对象。也许有一种方法可以保存文件中的所有信息,同时占用更少的内存?这是我的一些代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Beer
{
public:
string name;
string rating;
string country;
string alc;
string type;
};
int main() //Function uses ''bytes of stack/exceeds analyze:stacksize '16384'.
//Consider moving some data to heap
{
ifstream file("beer.txt");
if (!file.good())
{
cout << "Error. File was not found." << endl;
exit(EXIT_FAILURE);
}
else
{
int count;
string line;
ifstream file("beer.txt");
int count = 0;
for (int i = 0; !file.eof(); i++)
{
getline(file, line);
count++;
}
const int SIZE = count; //<- this is the place i'm struggling with
Beer allBeers[SIZE]; //expression must have a constant value
Beer currentBeer;
for (int i = 0; !file.eof(); i++)
{
getline(file, currentBeer.name, '\t');
getline(file, currentBeer.rating, '\t');
getline(file, currentBeer.country, '\t');
getline(file, currentBeer.alc, '\t');
getline(file, currentBeer.type, '\n');
allBeers[i] = currentBeer;
}
}
file.close();
return 0;
}
【问题讨论】:
-
为什么你想要一个编译时数组?特别是因为您在编译时没有信息。您正在运行时从文件中读取它们。
-
那么大的就是多余的
-
请定义限制(总是)。 IE。允许的最小输入大小和最大输入大小是多少。 beers.txt 的最大长度是多少——1GB?更多的?突然之间,基于堆栈的数组变得不是一个好主意。
-
当学习从一些现实生活的需求开始。例如数据库之类的需求。 IE。 “显示所有等级为 5 且国家/地区为‘英国’的熊”。
-
我的意思显然是“啤酒”而不是“熊”......干杯:)
标签: c++ arrays class memory compile-time