Pretoript

maxfromfile

Jan 8th, 2022
1,587
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. int main()
  5. {
  6.     const int WRONG_INPUT_FILE = 1;
  7.     const int WRONG_OUTPUT_FILE = 2;
  8.     const int INPUT_FILE_EMPTY = 3;
  9.  
  10.     std::ifstream input("input.txt");
  11.  
  12.     if(!input)
  13.     {
  14.         std::cout << "Wrong input file.\n";
  15.         return WRONG_INPUT_FILE;
  16.     }
  17.  
  18.     if(input.peek() == std::ifstream::traits_type::eof()) // Ez a videóban nem szerepelt, de így vizsgálhatjuk meg, hogy üres-e a fájl.
  19.     {
  20.         std::cout << "The input file is empty.\n";
  21.         return INPUT_FILE_EMPTY;
  22.     }
  23.  
  24.     int max;
  25.     input >> max; // Fájlban lévő első érték beolvasása max-ba.
  26.  
  27.     while(!input.eof()) // Használjuk inkább ezt a sima (input) helyett: azt nézi, hogy nem értünk-e a fájl végére: eof = end of file
  28.     {
  29.         int actual;
  30.         input >> actual;
  31.         if(actual > max) // Végigolvasva a fájlt, mindig frissítjük max értékét, ha az aktuálisan olvasott érték nagyobb annál.
  32.         {
  33.             max = actual;
  34.         }
  35.     }
  36.  
  37.     std::ofstream output("output.txt");
  38.  
  39.     if(!output)
  40.     {
  41.         std::cout << "Wrong output file.\n";
  42.         return WRONG_OUTPUT_FILE;
  43.     }
  44.  
  45.     output << "The max value is: " << max << "\n"; // Végül maxot beleírjuk egy output fájlba.
  46.     std::cout << "The program was successfull. Result is in output.txt.\n";
  47.  
  48.     return 0;
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment