从文本文件中读取行数,并将其存储为数组大小为c++的常量int
Read amount of lines from a text file and store them as a constant int for array size c++
我是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));
相关文章:
- 多维数组存储三种不同的数据类型?
- C++将原始字符数组存储在元组中
- 将十六进制字符数组存储在字节数组中,而无需更改为 ASCII 或其他任何东西
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- 如何将元素的索引从2D数组存储到1D数组中,然后交换这些值
- 如何将JSON数组存储在Arduino程序中
- 如何在AVR(例如:ATMega)或Arduino微控制器上制作2D PROGMEM阵列的1D PROGMEM数组(存储
- 使用 char 数组存储数据
- 使用平面数组存储的元组容器
- 数组 存储并要求用户搜索它
- 将值从一个 char 数组存储到另一个 char 数组
- 如何使字符串数组存储在向量中
- 将构造的静态数组存储在多个文件中的内存中
- 将整数数组存储在堆上并通过指针访问它们
- c++声明一个数据类型的字节数组,该数组存储在字符串中
- 使用指针数组存储阶乘计算的所有中间结果
- 使用异构数组存储不同的子类
- 读取文件内容,存储在数组中,向数组添加更多内容,然后将新数组存储在文件C++中
- 尝试将复杂数组存储到类 c++ 中
- 在字节数组存储中嵌入 int/string