As in c we can use various format specifiers like
So is there any way to use these with std::cout ?
I got some negative feedback in a recent course (c++ for c programmers) in coursera, for using printf instead of cout because i wanted to some formatting :(
For %nd
%0nd
, C++ equivalents are std::setw()
and std::setfill()
.
#include <iostream> // std::cout, std::endl
#include <iomanip> // std::setfill, std::setw
int main () {
std::cout << std::setfill ('x') << std::setw (10);
std::cout << 77 << std::endl;
return 0;
}
Output: xxxxxxxx77
%.nf
can be replaced by std::setprecision
and std::fixed
,
#include <iostream> // std::cout, std::fixed, std::scientific
int main () {
double a = 3.1415926534;
double b = 2006.0;
double c = 1.0e-10;
std::cout.precision(5);
std::cout << "fixed:\n" << std::fixed;
std::cout << a << '\n' << b << '\n' << c << '\n';
return 0;
}
Output:
fixed:
3.14159
2006.00000
0.00000