Open In App

std::setbase, std::setw , std::setfill in C++

The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. 
 

std::setbase (int base);
decimal : if base is 10
hexadecimal : if base is 16
octal : if base is 8
zero : if base is any other value.
// CPP Program to illustrate
// std::setbase manipulator
#include <iostream>
#include <iomanip> // std::setbase

int main()
{
    // set base to hexadecimal
    std::cout << std::setbase(16);

    // displaying 255 in hexadecimal
    std::cout << 255 << std::endl;

    // set base to Octal
    std::cout << std::setbase(8);

    // displaying 255 in Octal
    std::cout << 255 << std::endl;
    return 0;
}
ff
377
std::setw (int n);
where n is Number of characters to
be used as field width.
// CPP Program to illustrate
// std::setw manipulator
#include <iostream>
#include <iomanip> // std::setw

int main()
{

    // set width of 10
    std::cout << std::setw(10);
    std::cout << 100 << std::endl;

    std::string str = "GFG";

    // set width of 12
    std::cout << std::setw(12);

    std::cout << str << std::endl;
    return 0;
}
       100
GFG
#include <iostream>
#include<iomanip>
#include<string>
using std::cout;
using std::string;
using std::endl;

int main() {
    string temp="Hello setw";
    cout<<std::setw(5)<<temp<<endl;
    return 0;
}
Hello setw
std::setfill (char_type c);
char_type is the type of characters
used by the stream (i.e., its first class template
parameter, charT).
// CPP Program to test std::setfill manipulator
#include <iostream>
#include <iomanip> // std::setfill, std::setw

int main()
{
    // setfill is x and width is set as 10
    std::cout << std::setfill('x') << std::setw(10);

    std::cout << 77 << std::endl;

    std::string str = "Geeks";

    // setfill is G and width is set as 10
    // And std::left is used set str to left side
    std::cout << std::left << std::setfill('G') << std::setw(10);

    std::cout << str << std::endl;
    return 0;
}
xxxxxxxx77
GeeksGGGGG


Pattern using std::setw and std::fill

// CPP Program to print
// pattern using std::setw and std::fill
#include <iostream>
#include <iomanip> // std::setfill, std::setw

int main()
{
    int n = 5;
    for (int i = 1; i <= n; i++) {
        std::cout << std::left << std::setfill(' ') << std::setw(n);
        std::cout << std::string(i, '*') << std::endl;
    }
}

Output: 

*
**
***
****
*****


Article Tags :
C++