-3

So I need to define a constant by a variable so I can use that value in the definition of an array. Will this work?

std::fstream scores("scores.txt");
int numberOfLines;
std::string temp;

while (std::getline(scores, temp))
{
    numberOfLines++;
}

const int numberOfLines1 = numberOfLines;
int scoresArr [numberOfLines1] = {};
scores.close();
max66
  • 65,235
  • 10
  • 71
  • 111

2 Answers2

2

Will this work?

Short answer: no.

Long answer.

A C-style array need (in standard C++) a compile-time-known size.

So

// ............vvvvvvvvvvvvvv  <-- compile time constant, please
int scoresArr [numberOfLines1] = {};

numberOfLines1 must be known compile-time.

Unfortunately, in your code, numberOfLines1's value isn't known compile time but it's clearly uninitialized (so starts with an undefined value)

int numberOfLines;  // <-- initialized with an undefined value

and incremented a number of times that depends from an external file, so incremented necessarily run-time

while (std::getline(scores, temp))
{
    numberOfLines++;
}

So: no, doesn't works.

max66
  • 65,235
  • 10
  • 71
  • 111
0

You could use int *scoresArr = new int[numberOfLines1];

and free the space afterwards with delete [] scoresArr

wiomoc
  • 1,069
  • 10
  • 17