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

标签 c++ arrays inputstream constants

我是 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/

相关文章:

java - Java中的多项——可重用性和可维护性

java - 在 InputStream#close() 上使用 finally 关键字

java - 当我关闭 BufferedInputStream 时,底层的 InputStream 是否也关闭了?

Java - UDP 通过套接字发送数据.. 不推荐。所有数据

c++ - MFC中m_pMainWnd改为NULL

c++ - 是否有可能以类似于 Boost.MinimalTestFacility 的方式在 main 中调用 Boost.Unit Test 测试?

c++ - 使用捆绑属性作为 dijkstra_shortest_paths 中的权重图

c++ - 无法捕获异常!

c - 如何为任意大小的定长 C 字符串数组分配内存

php - 在 PHP 中将一个键分离两个数组值并插入到数据库