Open In App

How to Right Justify Output in C++?

Last Updated : 21 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, the outputs produced by the program are by default to the left of the screen. In this article, we will learn how to right justify the output in C++.

Example:

Input:
float x= 123.45
float y= 6.7899

Output:
123.45
6.7899 // justified on the console’s right side.

Right Justifying the Output in C++

To right justify the output in C++, we can use the std::right function which is one of the stream manipulators that sets the position of fill characters in conjunction with the std::setw manipulator function, which sets the stream width to the specified number of characters passed as an integral argument to this method.

C++ Program to Right Justify the Output

The below program demonstrates how we can justify the output values on the right side of the console in C++.

C++
// C++ program to right justify the output

#include <iomanip> // for  input-output manipulation
#include <iostream>
using namespace std;

int main()
{

    // Declare and initialize floating-point variables.
    float x = 123.45;
    float y = 6.7899;
    float z = 34.789;

    // Print each floating-point number with a width of 10
    // and aligned to the right.
    cout << setw(50) << right << x << endl;
    cout << setw(50) << right << y << endl;
    cout << setw(50) << right << z << endl;

    return 0;
}

Output
                                            123.45
                                            6.7899
                                            34.789

Time Complexity: O(1)
Auxilliary Space: O(1)




Next Article
Practice Tags :

Similar Reads