Guest User

working with filestreams

a guest
Aug 27th, 2016
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3.  
  4. //This program demonstrates using ifstream and ostream objects.
  5. //It opens a file with purely numeric input, separated by spaces, then
  6. //loads them into a vector, increments them, and overwrites the file
  7. //with new data formatted into three columns.
  8.  
  9. int main()
  10. {
  11.   std::ifstream readFile("Text.txt");
  12.   std::vector<int> vec;
  13.   int temp;
  14.   while(readFile >> temp)
  15.   {
  16.     vec.push_back(temp);
  17.   };
  18.   readFile.close();
  19.  
  20.   for (auto& i : vec)
  21.     ++i;
  22.  
  23.   std::ofstream writeFile("Text.txt"); //overwrites contents!
  24.   for(unsigned i = 0; i < vec.size(); ++i)
  25.   {
  26.     writeFile << vec[i] << ' ';
  27.     if ((i + 1) % 3 == 0)
  28.       writeFile << '\n';
  29.   }
  30.   writeFile.close();
  31. }
  32.  
  33. /* Contents of "Text.txt":
  34. 0 0 0
  35. 1 1 1
  36. 2 2 2
  37. 3 3 3
  38. 4 4 4
  39. */
Add Comment
Please, Sign In to add comment