How to receive input from the console then output it to a file with c++

My learning of c++ programming language has reached the critical stage and today I would like to show you a simple program which I have created with c++ which will receive input from a user and then output it to a file that user has just created.

#include <iostream>
#include <fstream>

#define LINE_WIDTH 100

using namespace std;

int main()
{
    int n;

    char filename[FILENAME_MAX]; //the character array to keep the name of the file

    char input_line[LINE_WIDTH]; //the character array to receive input from the user

    cout << "Enter a file name and press ENTER: ";

    cin.getline(filename, FILENAME_MAX); //FILENAME_MAX is a predefined constant that specifies the maximum length for filename supported on each system.

    ofstream file_out(filename); //create a new file or open an existing file

    if (! file_out) {
        cout << filename << " could not be opened.";
        cout << endl;
        return -1; 
    }

    cout << "Enter text or Q to terminate" << endl;

    while(true) {
        cin.getline(input_line, LINE_WIDTH); //read in the entire line input from a user
        n = input_line[0];
        if(n == 'Q') {
           break;
        } else {
            file_out << input_line << endl;
        }
    }

    file_out.close(); //close the file

    return 0;
}

When we run the program it will ask us to enter text which will then get written into a text file we have just created.

create file with c++
create text file with c++
A text file has been created with the content we have just entered
A text file has been created with the content we have just entered

It has already been 3 days since I started to learn c++ and everything go so smooth which means I have not encountered with any difficulty yet during the c++ lesson. c++ is a wonderful language and I hope you will like it as well!

Like this post? Kindly share!