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 →
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.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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++?
Which C++ stream manipulators are sticky, and how do you turn them off?
What does setprecision actually do in C++, and why do I get scientific notation?
How do I build an aligned report in C++ whose columns don't drift?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →