Login    New User    Forgot Password    Help      

Output

GO TO INDEX

Output

In order to do both input or output, you must open a file before anything else occurs. The same as a variable, the stream you are using is a type. So here is a short program that shows some simple output to a text file.

Example

#include <iostream>
#include <fstream>
using namespace std;

int main () {

//declare the variable of type ofstream
//since you are dealing with output:
ofstream myfile;

//function to open the file which includes
//the file name:
myfile.open ("example.txt");

//check if the file is open with the is_open()
//function:
if(myfile.is_open()){

//preform the operation(s):
myfile << "Hello world! This is output!" << endl;

//function to close the file:
myfile.close();
}else{

//is_open() returned false and there is a problem:
cout << "Can't open the file!" << endl;
}

return 0;
}

The above program will simply open a text file for output (ofstream), check to see if the file is correctly opened, write a line to the file and close the stream.

Here is a bit more detail about the above programs functions.

open()

The open() function will simply open a file for either input or output. The above program did it for output. The parameter of the function will be the file name. If the file does not exist in the directory, C++ will create it for you.

close()

A simple function designed to close the file and it's stream. It will require no parameters.

is_open()

The is_open() function is a boolean function that will check whether or not a file is open. If the function returns true, the file is open without any problems. If it returns false, the file is not good and therefore cannot be used.

GO TO INDEX