I'm trying to read the contents of a file object into an array of strings, but whatever I try nothing is displayed when I print the contents of the array. Specifically, I want to print the last ten lines of the text file by passing them into the array, and using a for loop on the array.
void FileReader::displayLast10records(){
ifstream ifile(filename);
string myArray[26];
cout << "\n" << filename << ": LAST 10 records in file \n\n";
for (int i = 0; i < numrecords; i++)
getline(ifile, myArray[i]);
ifile.close();
if (numrecords < 10)
{
for (int i = 0; i < numrecords; i++)
cout << setw(2) << (i + 1) << ".\t" << myArray[i] << endl;
}
else if (numrecords > 10)
{
for (int i = (numrecords - 10); i < numrecords; i++)
{
cout << setw(2) << (i + 1) << ".\t" << myArray[i] << endl;
}
}
}
The file(s) are simply large blocks of text, including spaces. The file looks like:
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely. The earliest programming languages predate the invention of the computer, and were used to direct the behavior of machines such as Jacquard looms and player pianos. Thousands of different programming languages have been created, mainly in the computer field, with many being created every year. Most programming languages describe computation in an imperative style, i.e., as a sequence of commands, although some languages, such as those that support functional programming or logic programming, use alternative forms of description.
I want to read each line into it's own element of a string array.
I do have another function that successfully uses getline() to display each line of the text file 10 lines at a time.
void FileReader::displayAllRecords(){
ifstream ifile(filename);
int displayed_lines = 0;
string arec;
cout <<"\n" << filename << ": ALL records in the file with line numbers, 10 at a time \n\n";
while (getline(ifile, arec))
{
if(displayed_lines % 10 == 0 && displayed_lines >= 1)
system("pause");
cout << setw(2) << (displayed_lines + 1) << ".\t" << arec << endl;
displayed_lines++;
}
ifile.close();
}