Since you're reading words, and words are just groups of characters sepearted y white space, you could simplify as follows.
Read all the words into a container
print out the size of the container
print out the first 10 members of the container
print out the last 10 members of the container.
Here's a rough example using a vector:
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
|
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
cout << "File?" << endl;
string file_name;
cin >> file_name;
ifstream input_file(file_name.c_str());
vector<string> words;
string word;
while (input_file >> word)
{
words.push_back(word);
}
input_file.close();
cout << "Number of words = " << words.size() << endl;
cout << "First 10 words are: ";
for (int i = 0; i < 10 && i < words.size(); ++i)
{
cout << words[i] << ", ";
}
cout << endl;
cout << "Last 10 words are: ";
int i = words.size() - 10;
i = i > 0 ? i : 0;
for (; i < words.size(); ++i)
{
cout << words[i] << ", ";
}
cout << endl;
}
|
In your case, perhaps don't store everything, just store the 10, and a rolling buffer of the next 10, until the end, while keeping count of everything, that shoul make it more challenigng