C++ Course

Output Manipulation

Objectives

  • Output manipulation
  • Text files

Output manipulation

// Example program
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main() 
{
  // Setting width, Alignment and filler 
  cout << setw(10) << "ten" << "four" << "four" << endl;  
  cout << setw(10) << setfill('_') << "ten" << endl;
  cout << right << setw(10) << setfill('_') << "ten" << endl;
  cout << left << setw(10) << setfill('_') << "ten" << endl;
  
  // Numbers manipulations
  cout << setprecision(3) << "pi=" << 3.1415926 << "  e=" << 2.171 << endl;
  cout << setbase(16) << 32 << "  " << 40 << endl;  // Can use dec, oct, hex
  cout << showbase << hex << 32  << endl;
  
  cout << dec << setw(10) << setfill('0') << right << 17 << endl;
}

Files - Text files

// Example program
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

const string filename = "output.txt";
int main() 
{
  ofstream outFile(filename);
  outFile << 1 << endl << 2 << endl << 3 << endl;
  outFile.close();
  
  ifstream inFile(filename);
  int input;
  cout << "Reading: " << endl;
  while (inFile >> input)
     cout << input << endl; 
     
  inFile.close();
}
Made with Slides.com