Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8.     int num_of_lines = 0;
  9.     int count_2 = 0;
  10.     fstream file;
  11.     string input;
  12.     string string_array[10];
  13.     file.open("numbers.txt", ios::in);
  14.  
  15.     //this while loop is simply used to find the # of lines
  16.  in the file.
  17.     //its going to go getline all the lines till it hits a flag hopefuly eof.
  18.         getline(file, input);
  19.         while (file)
  20.         {
  21.             cout << input << endl;
  22.             getline(file, input);
  23.             num_of_lines++;
  24.         }
  25.  
  26.         //clear the eof / other tags
  27.         file.clear();
  28.         //reset position to the start of the file
  29.         file.seekg(0L, ios::beg);
  30.         //now i know how many lines in the file, this loop does getline untill
  31.         //it reaches the line we wish to start saving (total lines - the number of lines we want)
  32.         for (int count = 0; count < (num_of_lines - 4); count++)
  33.         {
  34.             //its count_2 not count
  35.             count_2++;  //used in the next loop to ge the last lines.
  36.             getline(file, input);
  37.         }
  38.         int i = 0; // used in this next sectin to incremeptn string_array subscript to hold values.
  39.         //now we know how many lines total in the file, and getline is
  40.         //last loop to now collect the lines we wanted. count_2 is = to the position we start from.
  41.         // and num_of_lines is the total amount of lines so we just got the lines inbetween left.
  42.         for(count_2; count_2 < num_of_lines; count_2++)
  43.         {
  44.             getline(file, input);
  45.             string_array[i++] = input;  //the lines inbetween count_2 and the num_of_lines is saved in string array.
  46.         }
  47.        
  48.     cout << "SWEET\n"; //omg it worked!
  49.     //printing contents of the string array.
  50.     for (auto k : string_array)
  51.     {
  52.         cout << k << endl;
  53.     }
  54.     cout << "\nNumber of lines = " << num_of_lines << endl;
  55.  
  56.     file.close();
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement