Take input from the user and save it in a .txt file in C++

In this tutorial, we will learn how to take input from users and save that in a .txt file in C++. While writing this program we use fstream and create a txt file named new file and write the code.

Program to save texts in a txt file in C++ from user input

Here firstly we have to create a file named newfile. In order to write into text first, we need to open the file. There will be two parameters to be shown there, firstly the name of the file and secondly, it tells whether it should be in read mode, write mode. And the program below shows how to add the text and also we can enter in a similar way in the second line. After its completion, the file should be closed.


using namespace std;
int main()
    fstream newfile;
    if (newfile.is_open())
        newfile<<"Hello ,This is my first line"<<endl;
        newfile<<"This is my second line in my file"<<endl;

You can also read: How to get the file creation date of a file in C++

One response to “Take input from the user and save it in a .txt file in C++”

  1. Ajinkya says:

    My Doubt is How To Write Console Output in Txt File

Leave a Reply

Your email address will not be published. Required fields are marked *