Programming Language & Its Applications β Virtual Functions and File Handling, NEC licence examination syllabus (Nepal Engineering Council).
Format controls you place directly in the output stream β plus how to write your own.
cout.setf(...) on its own line breaks the flow of an output statement, and a single misplaced call pollutes formatting everywhere downstream. Manipulators put the format inline, where you can see it next to the data. Search "C++ iomanip cheat sheet" for the full list, and "std::format C++20" for the modern replacement β knowing both is now expected.#include <iostream>
#include <iomanip>
#include <string>
int main() {
/* ---- WIDTH and FILL ---- */
std::cout << " |" << std::setw(10) << 42 << "|\n";
std::cout << " |" << std::setw(10) << std::setfill('*')
<< 42 << "|" << std::setfill(' ') << "\n";
/* setw is spent by ONE item β the classic trap */
std::cout << " |" << std::setw(10) << 1 << 2 << 3 << "|\n";
std::cout << " |" << std::setw(4) << 1 << std::setw(4) << 2
<< std::setw(4) << 3 << "|\n";
/* ---- ALIGNMENT ---- */
std::cout << " left |" << std::left << std::setw(10)
<< "Ram" << "|\n";
std::cout << " right |" << std::right << std::setw(10)
<< "Ram" << "|\n";
std::cout << " intrn |" << std::internal << std::setw(10)
<< std::setfill('0') << -42 << "|"
<< std::setfill(' ') << std::right << "\n";
/* ---- FLOATING POINT: three modes ---- */
double x = 1234.56789;
std::cout << " default " << x << "\n";
std::cout << " prec(3) " << std::setprecision(3) << x << "\n";
std::cout << " fixed(3) " << std::fixed
<< std::setprecision(3) << x << "\n";
std::cout << " sci(3) " << std::scientific << x << "\n";
std::cout << " hexfloat " << std::hexfloat << x << "\n";
std::cout << std::defaultfloat << std::setprecision(6);
/* ---- BASES ---- */
int n = 255;
std::cout << " 255: dec=" << std::dec << n
<< " oct=" << std::oct << n
<< " hex=" << std::hex << n << "\n";
std::cout << " showbase : " << std::showbase
<< std::oct << n << " " << std::hex << n << "\n";
std::cout << " uppercase: " << std::uppercase
<< std::hex << n << "\n";
std::cout << std::nouppercase << std::noshowbase << std::dec;
/* ---- SIGN, POINT, BOOL ---- */
std::cout << " showpos : " << std::showpos << 42
<< " " << -42 << std::noshowpos << "\n";
std::cout << " showpoint : " << std::showpoint << 5.0
<< std::noshowpoint << "\n";
std::cout << " boolalpha : " << std::boolalpha << true
<< " " << false << std::noboolalpha << "\n";
/* ---- quoted (C++14) ---- */
std::string s = "he said \"hi\"";
std::cout << " raw : " << s << "\n";
std::cout << " quoted : " << std::quoted(s) << "\n";
return 0;
}
Output:
| 42|
|********42|
| 123|
| 1 2 3|
left |Ram |
right | Ram|
intrn |-000000042|
default 1234.57
prec(3) 1.23e+03
fixed(3) 1234.568
sci(3) 1.235e+03
hexfloat 0x1.34a4587e7c06ep+10
255: dec=255 oct=377 hex=ff
showbase : 0377 0xff
uppercase: 0XFF
showpos : +42 -42
showpoint : 5.00000
boolalpha : true false
raw : he said "hi"
quoted : "he said \"hi\""
setprecision(2) on a price of 1250.00 does not give "1250.00" β it gives "1.2e+03". Money formatting is always std::fixed << std::setprecision(2), both together. If you remember one line from this article, make it that one.
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
struct Row {
int roll;
std::string name;
double theory, practical;
};
int main() {
std::vector<Row> rows = {
{101, "Ram Bahadur", 68.5, 22.0},
{102, "Sita Devi", 71.0, 24.5},
{103, "Hari Prasad", 55.5, 18.0},
{104, "Gita Kumari", 47.0, 15.5},
{105, "Bikash Thapa", 78.0, 23.0}
};
const double FULL = 100.0;
/* --- title, centred by hand --- */
const int W = 62;
std::string title = "NEC LICENCE EXAM - RESULT SHEET";
std::cout << std::setw((W + title.size()) / 2) << title << "\n";
std::cout << std::setfill('=') << std::setw(W) << "" << "\n"
<< std::setfill(' ');
/* --- header row --- */
std::cout << std::left << std::setw(6) << "Roll"
<< std::left << std::setw(16) << "Name"
<< std::right << std::setw(9) << "Theory"
<< std::right << std::setw(10) << "Practical"
<< std::right << std::setw(8) << "Total"
<< std::right << std::setw(7) << "%"
<< std::right << std::setw(6) << "Grade" << "\n";
std::cout << std::setfill('-') << std::setw(W) << ""
<< "\n" << std::setfill(' ');
std::cout << std::fixed << std::setprecision(2);
double sumPct = 0; int passed = 0;
for (const auto &r : rows) {
double total = r.theory + r.practical;
double pct = total / FULL * 100.0;
const char *grade = pct >= 80 ? "A"
: pct >= 70 ? "B"
: pct >= 60 ? "C"
: pct >= 50 ? "D" : "F";
sumPct += pct;
if (pct >= 50) passed++;
std::cout << std::left << std::setw(6) << r.roll
<< std::left << std::setw(16) << r.name
<< std::right << std::setw(9) << r.theory
<< std::right << std::setw(10) << r.practical
<< std::right << std::setw(8) << total
<< std::right << std::setw(7) << pct
<< std::right << std::setw(6) << grade << "\n";
}
std::cout << std::setfill('-') << std::setw(W) << ""
<< "\n" << std::setfill(' ');
std::cout << std::left << std::setw(22) << "Class average"
<< std::right << std::setw(40 - 5)
<< sumPct / rows.size() << " %\n";
std::cout << std::left << std::setw(22) << "Passed"
<< std::right << std::setw(40 - 5)
<< passed << " / " << rows.size() << "\n";
return 0;
}
Output:
NEC LICENCE EXAM - RESULT SHEET
==============================================================
Roll Name Theory Practical Total % Grade
--------------------------------------------------------------
101 Ram Bahadur 68.50 22.00 90.50 90.50 A
102 Sita Devi 71.00 24.50 95.50 95.50 A
103 Hari Prasad 55.50 18.00 73.50 73.50 B
104 Gita Kumari 47.00 15.50 62.50 62.50 C
105 Bikash Thapa 78.00 23.00 101.00 101.00 A
--------------------------------------------------------------
Class average 84.60 %
Passed 5 / 5
#include <iostream>
#include <iomanip>
#include <string>
/* ---- 1. A SIMPLE manipulator: just a function ---- */
std::ostream& rupees(std::ostream &os) {
os << "Rs " << std::fixed << std::setprecision(2);
return os;
}
std::ostream& tab(std::ostream &os) { return os << '\t'; }
std::ostream& rule(std::ostream &os) {
return os << std::setfill('-') << std::setw(40) << ""
<< std::setfill(' ') << '\n';
}
/* ---- 2. A PARAMETERISED manipulator: a helper object
with its own operator<< ---- */
struct Pad {
int width;
char fill;
};
Pad pad(int w, char f = ' ') { return Pad{w, f}; }
std::ostream& operator<<(std::ostream &os, const Pad &p) {
os << std::setfill(p.fill) << std::setw(p.width);
return os;
}
/* a money manipulator carrying its own value */
struct Money { double amt; };
Money money(double a) { return Money{a}; }
std::ostream& operator<<(std::ostream &os, const Money &m) {
std::ios::fmtflags saved = os.flags();
std::streamsize prec = os.precision();
os << "Rs " << std::fixed << std::setprecision(2) << m.amt;
os.flags(saved); /* restore β no pollution */
os.precision(prec);
return os;
}
/* ---- 3. An RAII format guard ---- */
class FormatGuard {
std::ostream &os;
std::ios::fmtflags f;
std::streamsize p;
char c;
public:
explicit FormatGuard(std::ostream &s)
: os(s), f(s.flags()), p(s.precision()), c(s.fill()) {}
~FormatGuard() { os.flags(f); os.precision(p); os.fill(c); }
};
void dumpHex(std::ostream &os, int v) {
FormatGuard g(os); /* restores on ANY exit */
os << std::hex << std::showbase << std::uppercase << v;
}
int main() {
std::cout << " simple : " << rupees << 1234.5 << "\n";
std::cout << std::defaultfloat << std::setprecision(6);
std::cout << " param : |" << pad(12, '.') << "Ram" << "|"
<< pad(8, '0') << 42 << "|\n";
std::cout << " money : " << money(45.5) << " and "
<< money(1250) << "\n";
/* the stream is UNPOLLUTED afterwards: */
std::cout << " after : " << 3.14159265 << " (still 6 sig)\n";
std::cout << " hex : "; dumpHex(std::cout, 255);
std::cout << " then dec: " << 255 << " (guard restored)\n";
std::cout << rule;
std::cout << " a" << tab << "b" << tab << "c\n";
return 0;
}
Output:
simple : Rs 1234.50
param : |Ram.........|00000042|
money : Rs 45.50 and Rs 1250.00
after : 3.14159 (still 6 sig)
hex : 0XFF then dec: 255 (guard restored)
----------------------------------------
a b c
#include <iostream>
#include <sstream>
#include <chrono>
int main() {
const int N = 200000;
/* measured against a stringstream so we time the
formatting and flushing, not the terminal */
auto t0 = std::chrono::steady_clock::now();
{ std::ostringstream s;
for (int i = 0; i < N; i++) s << i << '\n'; }
auto t1 = std::chrono::steady_clock::now();
{ std::ostringstream s;
for (int i = 0; i < N; i++) s << i << std::endl; }
auto t2 = std::chrono::steady_clock::now();
using ms = std::chrono::duration<double, std::milli>;
std::cout << " " << N << " lines with '\\n' : "
<< ms(t1 - t0).count() << " ms\n";
std::cout << " " << N << " lines with endl : "
<< ms(t2 - t1).count() << " ms\n";
std::cout << " (to a real file or terminal the gap is\n"
<< " far larger, because each flush becomes\n"
<< " an actual write() system call)\n";
return 0;
}
Output (timings vary by machine):
200000 lines with '
' : 12.4 ms
200000 lines with endl : 31.8 ms
(to a real file or terminal the gap is
far larger, because each flush becomes
an actual write() system call)
The exact milliseconds depend on your machine β run it yourself. What is reliable is the direction and roughly the magnitude: endl costs meaningfully more, and the gap widens dramatically when the destination is a file or terminal rather than an in-memory stringstream, because then every flush is a real system call.
std::format puts the entire specification in one string β std::format("{:>10.2f}", x) replaces setw(10) << fixed << setprecision(2), affects no global state, checks the format string at compile time, and is typically several times faster because it avoids the virtual-call machinery. C++23 added std::print so you can write std::print("{} scored {:.1f}
", name, marks) directly. The format mini-language is borrowed from Python, so learning it once serves both languages. Search "std::format specification" and "fmtlib" (the library it came from, usable today in C++11).std::endl yourself (put('
') then flush()) β that is a favourite question. Separate the simple manipulators from the parameterised ones needing <iomanip>. The setw is not sticky trap and the setprecision alone gives scientific notation surprise are both high-value. Know endl versus '
' (flush cost) and be ready to write a custom manipulator, ideally one that restores the stream state.Create a free account to tick topics off, take notes as you read, watch the video lessons and get a day-by-day study plan built around your exam date.
Loadingβ¦