该程序从输入文件中读取文本。我的输出应该是:
Level Score Stars
----------------------------------
1 3840 **
2 5940 **
3 11560 **
4 18140 **
5 18780 **
它显示级别和分数,但问题是星星的显示。程序的其余部分显示星星而不是输出。
我似乎无法弄清楚为什么星星不断循环而不是输出?
#include <iostream> // access to cin, cout
#include <cstring>
#include <cstdlib>
#include<cmath>
#include <fstream>
using namespace std;
int buildArrays(int A[],int B[],int C[]) {
int a, i = 0; // (I think this is where the looping problem begins)
ifstream inFile;
inFile.open( "candycrush.txt" );
if ( inFile.fail() ) {
cout << "The candycrush.txt input file did not open";
exit(-1);
}
inFile >> a;
while(inFile) {
A[i] = a;
inFile >> a;
B[i] = a;
inFile >> a;
C[i] = a;
inFile >> a;
i++;
}
inFile.close();
return i;
}
void printArrays( string reportTitle, int levelsArray[], int scoresArray[], int starsArray[], int numberOfLevels ) {
cout << reportTitle << endl;
cout << "Levels\tScores\tStars" << 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() {
const int MAX=400;
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");
}