#include <iostream> #include <fstream> using namespace std; int getLastKLine(ifstream & fin, int k) { string line, lastK[k + 1]; int fix = 0; bool nolessThanK = false; while(getline(fin, line)) { lastK[fix++ % k] = line; if(!nolessThanK && fix >= k) nolessThanK = true; } if(!nolessThanK) k = fix; for(int i = 0; i != k; ++i) cout << lastK[i] << endl; } int main(void) { ifstream fin("1.txt"); int k = 3; getLastKLine(fin, k); return 0; }
1.txt
1111111111111111111111111111
2222222222222222222222222222
33333333333333333333333333
444444444444444444444444444
55555555555555555555555555
66666666666666666666666666666
7777777777777777777777777
888888888888888888888888
999999999999999999999999999