Search code examples
c++format-specifiers

Using various format specifiers of c in c++


As in c we can use various format specifiers like

  • %nd where n is a number, to print the number with a total of atleast n space covered
  • %0nd same as above, except pre-padding with 0's " %05d ",3 => 00003
  • %.nf to set precision of n after decimal
  • etc ....

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 :(


Solution

  • 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