我是 C++ 的新手,遇到了一些问题。基本上我要做的是读取不同类型的文本文件,并使用行数作为二维数组行的大小。
输入文件如下所示:
int_n1 int_n2 (These are 2 integers needed later on for processing)
(blank line)
[amount of nurses][140] (too much to type out)
链接到这里的实际情况 http://puu.sh/lEh2y/e4f740d30f.png
我的代码是这样的:
//maak inputStream klaar voor gebruik
ifstream prefFile(INPUTPREF);
//test of de inputstream kan geopend worden
if (prefFile.is_open())
{
// new lines will be skipped unless we stop it from happening:
prefFile.unsetf(std::ios_base::skipws);
// count the newlines with an algorithm specialized for counting:
unsigned line_count = std::count(std::istream_iterator<char>(prefFile),std::istream_iterator<char>(),'\n');
int aantNurse = line_count + 1 - 2;
int nursePref[aantNurse][140];
}
当然,仅仅将“const”放在“int aantNurse”前面是行不通的。 有人对如何解决这个问题有建议吗?我宁愿不必使用可以容纳所有东西的超大阵列,尽管这是可能的。
最佳答案
作为可能的解决方案之一,您可以为数组 nursePref
动态分配内存并在最后释放它。
就像这样:
int** nursePref = new int*[aantNurse];
for (int i = 0; i < aantNurse; ++i) {
nursePref[i] = new int[140];
}
然后使用delete[]
正确释放它:
for (int i = 0; i < aantNurse; ++i) {
delete[] nursePref[i];
}
delete[] nursePref;
此外,正如已经说过的,使用 vector 是一个更好的主意:
std::vector<std::vector<int> > nursePref(aantNurse, std::vector<int>(140));
关于c++ - 从文本文件中读取行数并将它们存储为数组大小的常量 int c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34003709/