Presenting Text Precisely, Explained with Code Examples

UPI Study › Courses › C++ Programming › Free lessons › Lesson 7.5 Free with a free account

Presenting Text Precisely

C++ Programming · Chapter 7: Text and Applied CollectionsSection 7.5 · lesson 47 of 84video coming soon

← The String Class ToolkitNext lesson: Validating User Input →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

In this lesson

Alignment, spacing, and display control.

  • Set a field width, and know it doesn't persist
  • Know which manipulators are sticky, and undo them
  • Control precision, and why it means two things
  • Build an aligned report whose columns can't drift

Transcript

Everything said in the video, section by section (1,332 words). Read along, or search it.

Opening Problem

Why Raw Output Needs Control

Sending values to the screen puts them there in whatever shape they happen to have. That's fine while a program is being written, and useless the moment anyone else has to read the output. A receipt whose amounts don't line up, or a table whose columns wander, is harder to check than the same numbers written by hand. The manipulators in this lesson are how a program takes control of that.

Before and After

Width and Precision Align Columns

Here are items printed with nothing but the insertion operator, against the same first item printed with field widths. Without formatting, the numbers run together, and nothing lines up. With formatting, every quantity, rate and amount sits in its own column. Nothing about the values changed. What changed is that each one was placed in a field of a stated width, and money was printed to a stated number of decimal places. Those two ideas, width and precision, carry most of this lesson. The tools live in the iomanip header, so a program using them includes that as well.

Field Width

Set w Affects Only One Item

Set w of n says the next item should occupy at least n character positions. If it needs fewer, the remaining positions are filled, by default with spaces, and by default placed before the value. So the value ends up right-aligned in its field. Here, a field of width 10 holds the four-character value Anya. The six unused positions are filled, not left out. And the width is a minimum, never a maximum. Now the rule that trips up everyone who meets these for the first time. Set w affects the very next item written, and is then forgotten. In the second line, A and B each get a width of 10, and C follows B directly. In the third, the width applied to A and nothing else, so B and C take whatever space they need. So a width you want on three items must be written once for each of them. It's the single most common cause of a broken table: columns look right on the first item, and collapse after that.

Sticky Settings

Which Manipulators Persist and Their Opposites

That distinction is worth stating once as a general property, because it decides how you have to write everything else. Set w lasts one item. Everything else is sticky. Set fill sets the padding character. Left and right put the fill after or before the value. Internal puts it between a leading sign and the digits. Set precision sets how many digits a fractional value shows. Fixed and scientific select the notation. And show point forces a decimal point and trailing zeros. Because these persist, each one has a counterpart that turns it off. Most show settings have a no partner: show point is undone by no show point. Forget the counterpart, and formatting from one part of a program leaks into an unrelated part later.

Padding Character

Set fill and Restoring the Space

Set fill replaces the padding character, which is how leader dots and rule lines get made. Being sticky, it applies to every field until changed back. Here, the dots fill each field of 10, and then the fill is put back to a space. There is no default-fill manipulator, so you set it back explicitly. Forget that, and a report with dot leaders leaves the dots behind: unrelated output afterwards comes out full of them.

Alignment

Right, Left, and Internal Placement

Alignment decides which side of the value the fill goes, and three settings exist. Right is the default, and correct for numbers, because it makes the units digits line up in a column. Left is correct for text: names and labels read badly when pushed to the right. And internal, which is rarely described, puts the fill between a leading sign and the digits. In ledger-style columns, the minus signs align on the left, and the digits on the right.

Precision

One Setting, Three Different Meanings

Set precision is the one manipulator whose meaning changes depending on another setting, which makes it the most misunderstood of the group. Take the value 1234.56789. In the default notation, set precision counts significant digits: every digit, on both sides of the point. Precision 3 gives 1.23e+03. Precision 8 gives 1234.5679. Under fixed, it counts digits after the point. Precision 2 gives 1234.57. Precision 0 gives 1235. Under scientific, it counts digits after the point in the leading part. And all of these are rounded, not cut off.

Currency

Fixed Plus Precision for Money

Currency wants exactly two digits after the point, always, including trailing zeros. That requires fixed, as well as the precision. The precision alone, in default notation, counts significant digits, and can produce scientific notation rather than an amount. The pair is written once, before the first amount, and being sticky, it holds for the rest of the report. 3.14159 prints as 3.14, and 2 prints as 2.00. A related setting is show point. By default, a value with nothing after the point prints without one: 5.0 appears simply as 5. Show point forces the point and the trailing digits to appear. Under fixed, they already do, so the two are rarely combined.

Overflow

When Values Exceed Their Fields

Set w sets a minimum. A value too large for its field is printed in full, pushing everything after it out of position. Anya fits her field. Priyadarshini doesn't, so she's printed in full, and the closing bracket is pushed right. That's the correct behavior: silently discarding part of a value would be far worse than a misaligned line. But a table built from data you don't control can still come out ragged. If a column must never exceed its width, shorten the value yourself, using length and sub str. And leave room for the ellipsis in the arithmetic. Cutting to the full width, then adding three dots, produces a value three positions too long, which is the very problem being solved.

Worked Example

Assembling the Receipt Report

Everything so far assembles into the receipt. Two habits make reports like this maintainable. Name the widths once. Write the numbers into each statement, and widening a column means finding every place it appears. That includes the header, the rule line, and the totals row, which is exactly where a stale number hides. And set the sticky things before the loop. Fixed and the precision apply to the whole report, so they belong above it. Only the widths, and the per-column alignment, change from item to item. The rule line is an empty string, written in a field as wide as the whole table, with the fill set to a dash. The fill does all the work. Its width is 22 plus 5 plus 10 plus 12, which is 49. And the totals row uses one field spanning the first three columns, so the total lands in the amount column, aligned with the amounts above it.

Alternative Syntax

Member Functions Versus Manipulators

Every manipulator has an equivalent written as an operation on the stream itself. C out dot width 10 is the same as set w 10, and still applies to one item only. C out dot fill is the same as set fill, and c out dot precision is the same as set precision. You'll meet these in existing code, and they behave identically. The difference is purely one of writing. Manipulators sit inline in a chain, keeping the formatting next to the value it governs. The member form is a separate statement, so the setting and the value end up on different lines. Prefer the manipulators, and recognize the member form.

Quick Check

Predicting Width and Sticky Precision

Quick check. This sets fixed and a precision of 1, then writes two values after a single width of 6. What exactly does it print, spaces included? Pause and predict. Three spaces and 2.5, then 10.0 runs straight into it, with no gap. The width covered only the first value. The precision is sticky, so it covered both.

Key Takeaways

Summary of Formatting Habits

To summarize. Write set w before every single value that needs a column. Everything else is sticky, so set it once and undo it deliberately. For money, set fixed and a precision of 2, once, before the first amount. And remember that a width can only pad, never trim. Name your column widths, and compute the rule line from them.

About C++ Programming at UPI Study

C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Presenting Text Precisely

Why does setw only work on one item in C++?
The setw manipulator applies only to the very next item written, then the stream forgets it. After cout << setw(10) << "A" << "B", A is right-aligned in ten positions, but B follows it with no padding. A width needed on three columns must be written before each of the three values. Forgetting this is a common reason a table looks right on the first column and collapses afterward.
Which C++ stream manipulators are sticky, and how do you turn them off?
Every common formatting manipulator except setw is sticky: setfill, left, right, internal, setprecision, fixed, scientific, and showpoint all persist until changed. Most settings have an opposite, such as noshowpoint to undo showpoint. There is no default-fill manipulator, so restore padding with setfill(' '). Otherwise, formatting leaks into later output, such as dot leaders appearing everywhere.
What does setprecision actually do in C++, and why do I get scientific notation?
Setprecision means different things depending on the notation. In default notation it counts significant digits, so 1234.56789 with precision 3 prints 1.23e+03, which is why scientific notation can appear. Under fixed, it counts digits after the decimal point, so precision 2 prints 1234.57. Under scientific, it counts digits after the point in the leading part. Values are rounded, not cut off.
How do I build an aligned report in C++ whose columns don't drift?
Name each column width once as a constant and reuse it in the header, rows, rule line, and totals row. Set sticky formatting, such as cout << fixed << setprecision(2), once before the loop. Then write setw before every value, using left for text and right for numbers. For a rule line, print an empty string with setfill('-') and a width equal to the sum of the column widths, then restore the space fill.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in C++ Programming.

84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

C++ Programming
3 credits · NCCRS
Enroll →