---
title: 2.10 Field Width
description: "The field width determines the minimum number of character positions used to display a value. If the value occupies fewer characters than the specified width, additional spaces are added to align the output. The `std::setw()` manipulator, provided by the ``…"
url: "https://edcret.in/docs/cpp-programming/input-and-output-cplusplus/2-10-field-width/"
updated: "2026-07-28"
category: C++ Programming / Input and Output
---

# 2.10 Field Width

The field width determines the minimum number of character positions used to display a value. If the value occupies fewer characters than the specified width, additional spaces are added to align the output.

The `std::setw()` manipulator, provided by the `<iomanip>` library, sets the field width for the next output operation only. It is commonly used to create neatly aligned tables and formatted reports.

## Source Code

```
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::setw(10) << "Name"
              << std::setw(8) << "Age" << '\n';

    std::cout << std::setw(10) << "Alice"
              << std::setw(8) << 24 << '\n';

    std::cout << std::setw(10) << "Bob"
              << std::setw(8) << 31 << '\n';

    return 0;
}
```

## Output

```
      Name     Age
     Alice      24
       Bob      31
```

## Explanation

- `#include <iomanip>` includes the header that provides formatting manipulators.
- `std::setw(width)` specifies the minimum field width for the next output value.
- If the output value is shorter than the specified width, leading spaces are added by default.
- If the output value is longer than the specified width, the entire value is printed without truncation.
- The effect of `std::setw()` applies only to the next insertion operation and must be specified again for subsequent values.
- Field width is commonly used to align columns in tabular output.
- `std::cout` displays the formatted data on the console.
- `return 0;` terminates the program successfully.
