1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
#include<iomanip>
#include<fstream>
#include<string>
#include<cstring>
using namespace std;
const int MAX_COLUMNS = 5;// The maximum amount of columns is 5
int readFile(double, int, string);// The function readFile has a double array, int, and string as parameters
int main()
{
string fileName;//The name of the file to be opened
int numActualRows = 0,//A variable to store the amount of rows within the array
const int MAX_ROWS = 20;//The maximum amount of rows that can be within the array
double values[MAX_ROWS][MAX_COLUMNS],// The array that will hold the contents of the file
cin >> fileName;/*The name of the file is read in, and is used as the argument when readfile() is called. The previously declared array along with the file name are also used as arguments. */
//The value returned by readFile(); is stored within numActualRows.
numActualRows = readFile(values, MAX_ROWS, fileName);
cout << numActualRows;
return 0;
}
int readFile(double values[][MAX_COLUMNS], int maxRows, string inputFileName)
{
ifstream myFile; // The file used to populate the array
int rowsRead = 0;// A variable to store the amount of rows read via data processing
myFile.open(inputFileName);//The file is opened, specified by the user
if(myFile)//If it is a valid file, process until end of file
{
//While data is processed, a loop is used to populate the array.
while(myFile)
{
for(int currentCollumn = 0; currentCollumn < MAX_COLUMNS; currentCollumn++)
{
myFile >> values[rowsRead][currentCollumn];
if(currentCollumn % 5 == 0)
{
rowsRead++;//For every five columns, the amount of rows read is increased and the index of the first dimension is also supposed to increase.
}
if(rowsRead == 20)
{
break;//If the amount of rows read by the loop is 20, stop the loop
}
}
myFile.close();//When the loop ends, close the file
if(rowsRead == 0 || rowsRead < 5)
{
return 0;//If there is no or too little data in the file, return 0
}
else{
return rowsRead;//Otherwise, return the amount of rows read
}
}
}
else//Otherwise, the function returns -1
{
return -1;
}
}
|