Answers for "write to file c++\"

C++
30

c++ writing to file

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}
Posted by: Guest on November-09-2019
0

read and write file in c++

#include<iostream>
#include<fstream>

using namespace std;

int main()
{

    string fileName;
    int choice;
    cout << "Enter txt file name:\n";
    cin >> fileName;
    cout << "Enter number of command:\n";
    cout << "1. Write file\n";
    cout << "2. Read file\n";
    cin >> choice;

    if (choice == 1)
    {
            ofstream myfile;
            string text;
            myfile.open (fileName);
            cout << "Write text below: \n"; //file must have no text
            cin >> text;
            myfile << text;
            myfile.close();
    }else if (choice == 2)
    {
            ifstream file(fileName);
            string line;

            if (file.is_open())
            {
	            while (getline(file, line))
                {
        	       cout << line << endl;
                }
    }
    }
    return 0;
}
Posted by: Guest on April-28-2022

Browse Popular Code Answers by Language