Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. //takes in an fstream, a filename, two ints
  6. void temp(std::fstream &fs, const std::string &filename, int count)
  7. {
  8.     using namespace std;
  9.     int start, delta;
  10.  
  11.     //input start
  12.     cout << "Input the start point of deletion. Starts at 1, ends at " << count << endl;
  13.     cin >> start;
  14.     if(start < 1 || start > count) { cout << "You died" <<endl; return; }
  15.  
  16.     //input delta
  17.     cout << "Input how many messages you want to delete from the start point;"
  18.     << " Write 1 to delete only the one at the start; 0 to not delete anything; max value is " << count+1-start << endl;
  19.     cin >> delta;
  20.     if(delta < 0 || delta > count+1-start) { cout << "You died" << endl; return; }
  21.     if(delta == 0) return;
  22.  
  23.  
  24.  
  25.  
  26.     std::string fs_filename = filename + "_temp.txt"
  27.     std::string line;
  28.     while(getline(fs, line)) if(line.find('\r') != std::string::npos) line.erase(line.end()-1, line.end());
  29.     fs.clear(); fs.seekg(0);
  30.  
  31.  
  32.  
  33.     if(!fs.is_open())
  34.     {
  35.         std::cout << "error" << std::endl;
  36.         return;
  37.     }
  38.  
  39.     auto print_ = [&fs]()
  40.     {
  41.         int counter = 0; fs.clear(); fs.seekg(0);
  42.  
  43.         std::string line;
  44.         while(getline(fs, line)) std::cout << ++counter << ". "<< line << '\n';
  45.  
  46.         fs.clear(); fs.seekg(0);
  47.     };
  48.  
  49.     //print_();
  50.    
  51.     //make a fstemp file
  52.     std::fstream fstemp(fs_filename, std::fstream::out);
  53.     int counter(0);
  54.  
  55.  
  56.  
  57.     fstemp.close(); fstemp.open(filename, std::fstream::in | std::fstream::out);
  58.  
  59.     while(getline(fs, line)) {
  60.         if(++counter >= line_to_delete)
  61.             fstemp << line << '\n';
  62.     }
  63.  
  64.     fs.close(); fs.open(filename, std::fstream::out);
  65.  
  66.     while(getline(fstemp, line))
  67.     {
  68.         //std::cout << line;
  69.         fs << line;
  70.         //STILL couts nothing
  71.     }
  72.     //print_(); //prints nothing
  73.  
  74.     //test_temp.txt is empty after running it
  75.     //test.txt has expected output
  76.     std::remove(fs_filename.c_str());
  77.     return;
  78. }
  79.  
  80. int main()
  81. {  
  82.     std::string filename = "test";
  83.     filename += ".txt";
  84.     std::fstream fs(filename, std::fstream::in | std::fstream::out);
  85.  
  86.  
  87.     temp(fs, filename);
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement