C++

Setw Field Width in C++

The setw() function in C++ is used to modify the output stream’s field width. The output value for the next output value might have a minimum character requirement. The padding character (by default is a space) fills in the empty spaces if the value requires fewer characters than the supplied width. The insertion operator and the setw() function are frequently used to format the program output. Use the setw(5) number, for instance, to print a number with a minimum width of 5 characters. The setw() method is a helpful tool to manage the output of your program and making sure that it is clear and easy to read.

Implementation of Setw Field Width in C++

To learn how the setw field width works in C++ programming language, let’s first understand the syntax. The <iomanip> header file, which is required for the function to operate in your program, contains the setw() function. Here, “n” is the width of the field where the value is shown, and “value” is the data that we want to print. Any subsequent output is printed in a field of that width, padding it as necessary with spaces or with another padding character. The function sets the width of the next output field to “n” characters.

Demonstration of How to Use the Setw() Function in C++

Here is the first example that demonstrates how to use the setw() function to format the output of a program that prints the multiplication table of any input number. But before that, we first include the necessary header files. The <iomanip> is used to format the output, including the functions like setw() to set the field widths.

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << "Multiplication table of " << num << ":" << endl;
    for (int i = 1; i <= 10; ++i)
    {
        cout << setw(2) << i << " x " << setw(2) << num << " = " << setw(3) << i * num << endl;
    }
    return 0;
}

The user of this program is requested to input a number. Using setw() to style the output and ensure that it is aligned and clear to read, the program then outputs the multiplication table for that integer. The setw() function is used to set the field width for each value when the for-loop iterates over the numbers 1 through 10 and outputs each row of the multiplication table.

The first setw(2) sets the multiplier’s width to two characters. The second setw(2) sets the input number’s width to two characters. The third setw(3) sets the third value’s result of multiplication’s width to three characters.

Using setw() to set the field widths for each value, we ensure that the output is aligned and easy to read even if the multiplication results have different numbers of digits. For example, if the user enters the number 5, the output of the program is the table of 5 that is neatly formatted and easy to read as you can see in the following:

Demonstration of Monthly Expenses of a Household Works Using the Setw() Function

This code demonstrates how to use the setw() function from the library in C++ to format the output of a program that calculates the monthly expenses. The first four lines define the monthly expenses of a household: rent, groceries, utilities, and transportation. The total variable is calculated by adding these values together.

Setw() is used by the cout commands to format the program’s output. The first line sets the width of the “Expense Category” column to 20 characters and the “Amount” column to 10 characters. The left manipulator is used to left-align the text in each column. The subsequent lines use setw() to set the width of the expense category to 20 characters and the amount to 10 characters, with two decimal places.

With the fixed manipulator, the fixed-point notation is ensured and the number of decimal places is set to two with setprecision(). Furthermore, the return 0 statement indicates a successful run of the program via the main() function.

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    double rent = 800.0, groceries = 350.0, utilities = 200.0, transportation = 150.0;
    double total = rent + groceries + utilities + transportation;

    cout << left << setw(20) << "Expense Category" << setw(10) << "Amount" << endl;
    cout << left << setw(20) << "Rent" << setw(10) << fixed << setprecision(2) << rent << endl;
    cout << left << setw(20) << "Groceries" << setw(10) << fixed << setprecision(2) << groceries << endl;
    cout << left << setw(20) << "Utilities" << setw(10) << fixed << setprecision(2) << utilities << endl;
    cout << left << setw(20) << "Transportation" << setw(10) << fixed << setprecision(2) << transportation << endl;
    cout << left << setw(20) << "Total" << setw(10) << fixed << setprecision(2) << total << endl;
    return 0;
}

When this program is run, it outputs the monthly expenses in a neatly formatted table. The output looks like this:

The use of setw() in this program ensures that the output is well-formatted and easy to read, with each column of data aligned to the left and of the same width.

Formatting the Mathematical Constants with Setw() in C++

This example demonstrates how to format the output in C++ using the setw() function from the library. First, the C++ libraries are included for the input/output and manipulators. Text is outputted using cout and endl, while the output fields’ width is determined using setw(). The standard C++ keywords can be used without prefixing them with std:: using the namespace std; line.

Next, we take two double-precision floating point numbers, “pi” and “e”, which are initialized with the values of the mathematical constants “pi” and “e”. Then, cout is used to output the value of “pi” and “e”, along with a label for each constant. Formatting the output with a fixed number of decimal places is done using the fixed and setprecision() functions. In this case, the setprecision(4) is used to specify that the output should be formatted with four decimal places.

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    double pi = 3.14159265359;
    double e = 2.71828182845;
    cout << "The value of pi is: " << setw(10) << fixed << setprecision(4) << pi << endl;
    cout << "The value of e is: " << setw(10) << fixed << setprecision(4) << e < endl;
    return 0;
}

When the program is executed, the output is as follows:

Utilization of Setw() to Align the Columns in a Table

This code displays a table of names, ages, and countries. It uses the setw() function from the iomanip library to set the width of each column and the left function to align the text to the left side of the column. The cout statement in the main function prints out the table with three rows, each with three columns which contain the data of three people named Alice, Bob, and Charlie. The output is formatted so that each name, age, and country is left-aligned and padded with spaces to fit into the designated column width of 20 characters.

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    cout << left << setw(20) << "Name" << setw(20) << "Age" << setw(20) << "Country" << endl;
    cout << left << setw(20) << "Alice" << setw(20) << "25" << setw(20) << "USA" << endl;
    cout << left << setw(20) << "Bob" << setw(20) << "30" << setw(20) << "Canada" << endl;
    cout << left << setw(20) << "Charlie" << setw(20) << "20" << setw(20) << "Australia" << endl;
    return 0;
}

Here is the output of the illustrated program:

Conclusion

We learned one of the important functions of the C++ programming language which is the setw() function. We also learned the implementation of the setw() function and implemented some examples in detailed explanations so that we can easily understand the concept.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.