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 :: reverse level order traversal 
Cpp :: sina + sinb formula 
Cpp :: quick sort c+++ 
Cpp :: sizeof’ on array function parameter ‘arr’ will return size of ‘int*’ [-Wsizeof-array-argument] 
Cpp :: insert a character into a string c++ 
Cpp :: c++ min int 
Cpp :: how to square a number in c++ 
Cpp :: unreal engine c++ 
Cpp :: c++ get maximum value unsigned int 
Cpp :: arduino xor checksum 
Cpp :: argument vs parameter coding c++ 
Cpp :: power function c++ 
Cpp :: how to calculate bitwise xor c++ 
Cpp :: Search Insert Position leetcode solution in cpp 
Cpp :: opengl draw semi circle c++ 
Cpp :: C++ Conditions and If Statements 
Cpp :: c++ function as paramter 
Cpp :: all permutations with repetition C++ 
Cpp :: cpp detect os 
Cpp :: maxheap cpp stl 
Cpp :: how to use a non const function from a const function 
Cpp :: class operator overloading c++ 
Cpp :: tuple vector c++ 
Cpp :: cpp execute command 
Cpp :: c++ uint8_t header 
Cpp :: oncomponentendoverlap ue4 c++ 
Cpp :: c++ delay 
Cpp :: rethrow exception c++ 
Cpp :: minheap cpp stl 
Cpp :: Shuffle String leetcode solution in c++ 
ADD CONTENT
Topic
Content
Source link
Name
1+9 =