从文本文件中读取行数,并将其存储为数组大小为c++的常量int

Read amount of lines from a text file and store them as a constant int for array size c++

本文关键字:数组 存储 小为 c++ int 常量 文件 文本 读取      更新时间:2023-10-16

我是C++的新手,遇到了一些问题。基本上,我要做的是读取不同类型的文本文件,并使用行数作为二维数组行的大小。

输入文件如下所示:

int_n1 int_n2(这是稍后处理所需的2个整数)

(空行)

[护士人数][140](太多,无法打印)

链接到它的实际外观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 aantNature前面是行不通的。有人对如何解决这个问题有什么建议吗?我不想使用可以容纳所有东西的超大阵列,尽管这可能是可能的。

作为可能的解决方案之一,您可以为数组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;

此外,正如已经说过的,使用矢量是一个更好的想法:

std::vector<std::vector<int> > nursePref(aantNurse, std::vector<int>(140));