How to Print to a File in
C++
/*
Name:
PrintToFile
Author: your name goes here
Date:
Description: This is my first program and is to be handed in
The results will be sent to the printer
*/
#include <cstdlib>
#include <iostream>
#include
<fstream> //include library for
file processing
using namespace std;
int main()
{
string first, last;
ofstream outfile; //create an output file
outfile.open("output.txt"); //opens the file for output
//Note:
may be combined into a single
// statement -
// ofstream outfile("output.txt");
cout << "Please enter
your first and last name." << endl;
cout << "Do not forget
to press the ENTER key!" << endl
<< endl ;
cin >> first >> last;
//Use outfile
in place of cout
outfile << "This is my first
program!" << endl;
outfile << "My name is: " <<
first << " " << last << endl;
outfile.close(); // close the file
system("PAUSE");
return EXIT_SUCCESS;
}
How to read from a file in
C++
/*
Name: ReadFromFile
Copyright:
Author: Prof. Langsam
Date:
Description: Simple program to read numbers from a file and
display them on the screen
*/
#include <cstdlib>
#include <iostream>
#include
<fstream> //include library for
file processing
using namespace std;
int main()
{
float x;
ifstream infile; //create the file infile for input
infile.open("MyData.txt");
//Method: open the file
//Note: may be
combined into one statement -
// ifstream infile("MyData.txt");
if ( !infile.is_open() ) {
//Method: checks to see if file was opened
// The file
could not be opened
cout
<< endl << "ERROR: Unable to open
file" << endl;
system ("PAUSE");
exit(1);
}
infile >> x; //read from the file: use infile
instead of cin
while (x >= 0) {
cout << x
<< endl;
infile >> x;
}
// end while
infile.close(); //close the file
system("PAUSE");
return EXIT_SUCCESS;
}
Sample data file MyData.txt
4
3
56
32
67
0
1
2
-1