C++ Manipulators | Find output programs | Set 2

This section contains the C++ find output programs with their explanations on C++ Manipulators (set 2).
Submitted by Nidhi, on July 13, 2020

Program 1:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    cout << 3.123456789 << endl;
    cout << setprecision(3) << 3.123456789 << endl;

    return 0;
}

Output:

3.12346
3.12

Explanation:

Here, we used setprecision() manipulator then it sets the precision value. Here we used precision value 3, and then we print "3.12" instead of "3.123456789".

Program 2:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    unsigned char str[] = "World";
    cout << "Hello" << setw(7) << str;
    return 0;
}

Output:

Hello  World

Explanation:

Here, we used setw() manipulator which is used to set the width of the string. If the specified string has less character than setw(), then it will add spaces at the left side of the string.

In our example, size of the str is 5 and we used 7 in setw() then it will add 2 spaces on the left side.

Program 3:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    unsigned char str[] = "World";
    cout << "Hello" << setw(7) << str << str;
    return 0;
}

Output:

Hello  WorldWorld

Explanation:

Here, we used setw() manipulator which is used to set the width of the string. If the specified string has less character than setw(), then it will add spaces at the left side of the string.

Here, width is set only for 1st str in the cout statement. The 2nd str will be printed as it is. Then the final output "Hello  WorldWorld" will be printed on the console screen.

Program 4:

#include <iostream>
#include <iomanip>
#include <ios>
using namespace std;

int main()
{
    cout << setw(15) << setfill('*') << "includehelp" << setw(20) << setfill('#') << "tutorials" << endl;
    return 0;
}

Output:

****includehelp###########tutorials

Explanation:

Here, we used setw() and setfill() manipulators.

  • setw() : This is used to set the width of string that will be printed on the console screen.
  • setfill() : This is used to fill the specified character.

We set width 15 for string "includehelp" so 4 '*' are padded at the left side. And set 20 for string "tutorials" so 11 '#' is padded at the left side.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.