Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <string>
- using namespace std;
- int main()
- {
- int num_of_lines = 0;
- int count_2 = 0;
- fstream file;
- string input;
- string string_array[10];
- file.open("numbers.txt", ios::in);
- //this while loop is simply used to find the # of lines
- in the file.
- //its going to go getline all the lines till it hits a flag hopefuly eof.
- getline(file, input);
- while (file)
- {
- cout << input << endl;
- getline(file, input);
- num_of_lines++;
- }
- //clear the eof / other tags
- file.clear();
- //reset position to the start of the file
- file.seekg(0L, ios::beg);
- //now i know how many lines in the file, this loop does getline untill
- //it reaches the line we wish to start saving (total lines - the number of lines we want)
- for (int count = 0; count < (num_of_lines - 4); count++)
- {
- //its count_2 not count
- count_2++; //used in the next loop to ge the last lines.
- getline(file, input);
- }
- int i = 0; // used in this next sectin to incremeptn string_array subscript to hold values.
- //now we know how many lines total in the file, and getline is
- //last loop to now collect the lines we wanted. count_2 is = to the position we start from.
- // and num_of_lines is the total amount of lines so we just got the lines inbetween left.
- for(count_2; count_2 < num_of_lines; count_2++)
- {
- getline(file, input);
- string_array[i++] = input; //the lines inbetween count_2 and the num_of_lines is saved in string array.
- }
- cout << "SWEET\n"; //omg it worked!
- //printing contents of the string array.
- for (auto k : string_array)
- {
- cout << k << endl;
- }
- cout << "\nNumber of lines = " << num_of_lines << endl;
- file.close();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement