Advertisement
avr39ripe

cppFileIOTextAdv

Nov 3rd, 2021
1,016
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. //ofstream - output stream
  5. //ifstream - input stream
  6. //fstream - input/output stream
  7.  
  8. // std::ios::app
  9. // std::ios::trunc
  10. // std::ios::out
  11. // std::ios::in
  12. // std::ios::binary
  13.  
  14.  
  15.  
  16. struct Temp
  17. {
  18.     int id;
  19.     float temperature;
  20.     char desc[20];
  21. };
  22.  
  23. int main()
  24. {
  25.     const int tempsSize{ 3 };
  26.     Temp temps[tempsSize]{
  27.         {1, 0,"ice"},
  28.         {2, 100.0, "boil"},
  29.         {3, 26.6, "comfort"}
  30.     };
  31.  
  32.     std::ofstream outf;
  33.  
  34.     outf.open("d:\\file.txt", std::ios::trunc | std::ios::out);
  35.  
  36.     if ( !outf )
  37.     {
  38.         std::cout << "IOERROR: can't create/open file!\n";
  39.         return 1;
  40.     }
  41.  
  42.     for (int i{ 0 }; i < tempsSize; ++i)
  43.     {
  44.         //outf <<  temps[i].id << ' ' << temps[i].temperature << ' ' << temps[i].desc << '\n';
  45.         outf << temps[i].id << '\n' << temps[i].temperature << '\n' << temps[i].desc << '\n';
  46.     }
  47.  
  48.     outf.close();
  49.  
  50.     int idx{ 0 };
  51.  
  52.     Temp readTemps[tempsSize * 3];
  53.  
  54.     std::ifstream inf;
  55.  
  56.     inf.open("d:\\file.txt");
  57.  
  58.     if (!inf)
  59.     {
  60.         std::cout << "IOERROR: can't open file!\n";
  61.         return 1;
  62.     }
  63.        
  64.     while (!inf.eof())
  65.     {
  66.         inf >> readTemps[idx].id >> readTemps[idx].temperature >> readTemps[idx].desc;
  67.        
  68.        
  69.  
  70.         if (inf.fail())
  71.         {
  72.             if (inf.eof())
  73.             {
  74.                 break;
  75.             }
  76.  
  77.             inf.clear();
  78.             inf.ignore(100, '\n');
  79.         }
  80.  
  81.         std::cout << "Temps #" << readTemps[idx].id << ' '
  82.                                 << readTemps[idx].temperature << ' '
  83.                                 << readTemps[idx].desc << '\n';
  84.         idx++;
  85.     }
  86.    
  87.     inf.close();
  88.  
  89.     return 0;
  90. }  
  91.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement