Advertisement
vvccs

file handling read and write

Jun 6th, 2023 (edited)
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <limits>
  5.  
  6. using namespace std;
  7.  
  8. void writeFile(const string& filename) {
  9.     ofstream os(filename);
  10.     if (!os) {
  11.         cout << "Error opening the file for writing." << endl;
  12.         return;
  13.     }
  14.  
  15.     cout << "Enter a line of text: ";
  16.     string input;
  17.     getline(cin, input);
  18.     os << input << endl;
  19.  
  20.     cout << "Enter a word: ";
  21.     cin >> input;
  22.     cin.ignore(numeric_limits<streamsize>::max(), '\n');
  23.     os << input << endl;
  24.  
  25.     os.close();
  26. }
  27.  
  28. void readFile(const string& filename) {
  29.     ifstream is(filename);
  30.     if (!is) {
  31.         cout << "Error opening the file for reading." << endl;
  32.         return;
  33.     }
  34.  
  35.     string line;
  36.     while (getline(is, line)) {
  37.         cout << line << endl;
  38.     }
  39.  
  40.     is.close();
  41. }
  42.  
  43. int main() {
  44.     string filename = "Testout.txt";
  45.  
  46.     writeFile(filename);
  47.     readFile(filename);
  48.  
  49.     return 0;
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement