I keep getting an error that says ISO C++ forbids variable-size array.
I am suppose to have an output that displays
Level Score Stars
----------------------------------
1 3840 ***
and so on....
Here is my program
#include <iostream> // access to cin, cout
#include <cstring>
#include <cstdlib>
#include<fstream>
using namespace std;
int buildArrays(int A [], int B [], int C [])
{
int i = 0, num;
ifstream inFile;
inFile.open("candycrush.txt");
if (inFile.fail())
{
cout << "The candycrush.txt input file did not open" << endl;
exit(-1);
}
while (inFile)
{
inFile >> num;
A[i] = num;
inFile >> num;
B[i] = num;
inFile >> num;
C[i] = num;
i++;
}
inFile.close();
return i;
}
void printArrays(string reportTitle, int levelsArray [], int scoresArray [], int starsArray [], int numberOfLevels)
{
cout << endl;
cout << reportTitle << endl;
cout << "Levels\tScores\tStars" << endl;
cout << "---------------------" << endl;
for (int i = 0; i < numberOfLevels; i++)
{
cout << levelsArray[i] << "\t" << scoresArray[i] << "\t";
for (int j = 0; j < starsArray[i]; j++)
{
cout << "*";
}
cout << endl;
}
}
void sortArrays(int levelsArray [], int scoresArray [], int starsArray [], int numberOfLevels)
{
for (int i = 0; i < numberOfLevels; i++)
{
for (int j = 0; j < numberOfLevels; j++)
{
if (levelsArray[i] < levelsArray[j])
{
int temp1 = levelsArray[i];
int temp2 = scoresArray[i];
int temp3 = starsArray[i];
levelsArray[i] = levelsArray[j];
scoresArray[i] = scoresArray[j];
starsArray[i] = starsArray[j];
levelsArray[j] = temp1;
scoresArray[j] = temp2;
starsArray[j] = temp3;
}
}
}
}
int main()
{
int MAX = 400; (This is where I am getting my valid array size error)
int levelsArray[MAX];
int scoresArray[MAX];
int starsArray[MAX];
int numberOfLevels = buildArrays(levelsArray, scoresArray, starsArray);
printArrays("Candy Crush UNSORTED Report", levelsArray, scoresArray, starsArray, numberOfLevels);
sortArrays(levelsArray, scoresArray, starsArray, numberOfLevels);
printArrays("Candy Crush SORTED Report", levelsArray, scoresArray, starsArray, numberOfLevels);
system("pause");
}
const int MAX=400;g++compiler in the GNU Compiler Collection, aka GCC) allows VLAs by default, but the C++ standard does not. In standard C++, array bounds must be constants in contexts such as yourmain(). Using a variableMAXinstead of aconst int MAXmeans a VLA, even though it is always the same size (just because the dimension is not a constantint). Hence the warning, and hence the recommended fix.