Use cout to write to a specific file instead of to the standard display device - C++ File Stream

C++ examples for File Stream:cout

Description

Use cout to write to a specific file instead of to the standard display device

Demo Code

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <iomanip>
using namespace std;
int main()/* ww  w . j  a  v a2  s  . c o  m*/
{
   string filename = "prices.dat";
   ofstream outFile;
   outFile.open(filename.c_str());
   if (outFile.fail())
   {
      cout << "The file was not successfully opened" << endl;
      exit(1);
   }
   // Set the output file stream formats
   outFile << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(2);
   // Send data to the file
   outFile << "Hats "  << 3.95 << endl << "Bulbs " << 0.22  << endl << "Cases " << 11.08  << endl;
   outFile.close();
   cout << "The file " << filename << " has been successfully written." << endl;
   return 0;
}

Result


Related Tutorials