I have a really basic problem in c++, I’m reading a tab separated file and I want to declare an array with the dimension if the number of fields the file has (work with different files with different widths) so I need to read the first line and count the number of fields, I tried this:
while(getline(t, line));{
...
if(!flag)
{int array[size][5];
flag=1}
...
}
But then I get the error:
error: ‘array’ was not declared in this scope
I understand it is because the scope of the variable is in the if loop, is there any way to declare a null array and resize it? Or will I have to use pointers?
The size of an array must be a compile-time constant. Use a
std::vectorif you want a dynamically-sized array.Other issues with your code:
Remove the semicolon after the
while, or your loop body will only be executed once after the whole file is read.Add a semicolon after
flag=1.