[英]Read amount of lines from a text file and store them as a constant int for array size c++
I'm new to C++ and having some problems. 我是C ++的新手,遇到了一些问题。 Basically what I have to do is read different kinds of text files and use the amount of lines as the size for the rows of a 2-dimensional array.
基本上,我要做的是读取不同类型的文本文件,并将行数用作二维数组的行大小。
The input file looks like this: 输入文件如下所示:
int_n1 int_n2 (These are 2 integers needed later on for processing)
int_n1 int_n2(这些是稍后需要进行处理的2个整数)
(blank line)
(空行)
[amount of nurses][140] (too much to type out)
[护士人数] [140](输入的内容太多)
link to what it actually looks like here http://puu.sh/lEh2y/e4f740d30f.png 链接到此处的实际外观http://puu.sh/lEh2y/e4f740d30f.png
My code looks like this: 我的代码如下所示:
//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];
}
Of course, just putting 'const' in front of 'int aantNurse' doesn't work. 当然,仅将“ const”放在“ int aantNurse”之前是行不通的。 Does anybody have a suggestion on how to solve this?
有人对如何解决这个问题有建议吗? I'd prefer not to have to use an oversized array that could fit everything, although that could be a possiblity.
我希望不必使用可以容纳所有内容的超大数组,尽管这可能是可能的。
As one of the possible solutions you can allocate memory for your array nursePref
dynamically and release it in the end. 作为一种可能的解决方案,您可以为数组
nursePref
动态分配内存,最后释放它。
Just something like this: 就像这样:
int** nursePref = new int*[aantNurse];
for (int i = 0; i < aantNurse; ++i) {
nursePref[i] = new int[140];
}
Then release it properly using delete[]
: 然后使用
delete[]
正确释放它:
for (int i = 0; i < aantNurse; ++i) {
delete[] nursePref[i];
}
delete[] nursePref;
Also, as it's said already, using vectors is a better idea: 而且,正如已经说过的,使用向量是一个更好的主意:
std::vector<std::vector<int> > nursePref(aantNurse, std::vector<int>(140));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.