Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ write to file

// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile ("example.txt");
    myfile << "This is a line.
";
    myfile << "This is another line.
";
    myfile.close();
  return 0;
}
Comment

read and write file in c++

#include<iostream>
#include<fstream>

using namespace std;

int main()
{

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

    if (choice == 1)
    {
            ofstream myfile;
            string text;
            myfile.open (fileName);
            cout << "Write text below: 
"; //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;
}
Comment

How to write into files in C++

#include <fstream> 

/*
ofstream 	Creates and writes to files
ifstream 	Reads from files
fstream 	A combination of ofstream and ifstream: creates, reads, and writes to files
*/

int main() {
  // Create and open a text file
  ofstream MyFile("filename.txt");

  // Write to the file
  MyFile << "Files can be tricky, but it is fun enough!";

  // Close the file
  MyFile.close();
} 
Comment

PREVIOUS NEXT
Code Example
Cpp :: change const value c++ 
Cpp :: unknown type name pid_t 
Cpp :: c++ console color some digits 
Cpp :: char type casting in c++ 
Cpp :: C++ Fahrenheit to Kelvin 
Cpp :: program to convert int to int array c++ 
Cpp :: average of a matrix c++ 
Cpp :: how to delete a 2d dynamic array in c++ 
Cpp :: c++ nodiscard 
Cpp :: getline cin is being skipped 
Cpp :: random in range c++ 
Cpp :: c++ in linux 
Cpp :: qstring insert character 
Cpp :: c++ string to double 
Cpp :: how to access struct variables in c++ 
Cpp :: cpp rand 
Cpp :: math in section title latex 
Cpp :: separating class into header and cpp file 
Cpp :: cannot open include file: 
Cpp :: heap buffer overflow c++ 
Cpp :: sort function descending c++ 
Cpp :: reverse c++ string 
Cpp :: count word accurances in a string c++ 
Cpp :: 2d vector cpp 
Cpp :: cpp list 
Cpp :: use lower bound in pair vector 
Cpp :: conditional variable c++ 
Cpp :: how to create array with not constant size in cpp 
Cpp :: sieve of eratosthenes algorithm in c++ 
Cpp :: cpp std list example 
ADD CONTENT
Topic
Content
Source link
Name
5+3 =