Mastering Module 4

Output & String Handlings

Video Overview

Master Output and String Handling in C++! Learn to display text using the iostream library and cout. We cover String Literals, concatenating data with the insertion operator (<<), and formatting layouts using endl.

Goal: Displaying & Formatting Output.

🎉 You're almost at the finish line! Want the full notes?

Download PDF Notes

Notes

1. Visualizing Input vs Output

Confused by << and >>? Just follow the direction of the arrows!

  • Output (Push)
    Arrows point towards the output. Pushing data out to the screen.
  • Input (Pull)
    Arrows point towards the variable. Pulling data in from the keyboard.
cout
<< << <<
"Hello"
"Pushing 'Hello' to Cout"
cin
>> >> >>
x
"Pulling keyboard input into x"

2. Output & Escape Sequences

The cout Object

Used with the insertion operator << to display variables and strings.

Formatting with Escape Sequences

Special characters that control the cursor layout:

  • \n Newline: Cursor moves to the next line.
  • \t Tab: Cursor moves to the next tab stop.
  • \a Alert: Triggers a system beep.
  • \" Double Quote: Displays ".
Try it Yourself
Console Output
// Click Run to see output...

3. Built-in (Library) Functions

cmath

Math Functions

For complex calculations beyond + or -.

  • pow(2, 3) → 8.0
  • sqrt(16) → 4.0
  • abs(-5) → 5
string

String Manipulation

Handling text effectively.

  • str.length() : Size of string
  • str.substr(p, n) : Extract part
  • str.find('x') : Search index
iomanip

Input/Output Manipulation

Required for setw, setprecision, and fixed.

4. Formatted Output

setprecision(n)
Precision

Sets the number of decimal places to display. Best used with fixed.

setw(n)
Field Width

Spaces the next output into a field of n characters. Good for tables.

fixed / showpoint
Force Decimals

Forces the decimal point and trailing zeros to be shown on the screen.

Adjust Column Widths

Change the setw(n) values to see how the alignment shifts:

// The output is right-aligned within the width
cout << fixed << setprecision(2);
cout << setw(10) << "Price:" << setw(8) << 19.90 << endl;
cout << setw(10) << "Tax:" << setw(8) << 1.20 << endl;
Console Output
COLUMN RULER (1 character per dot)
          Price:    19.90
            Tax:     1.20

Pro Tip: If the setw number is smaller than the word (e.g., setw(2) for "Price"), C++ will ignore the width and print the whole word anyway!

Advanced Formatting: setfill

While setw creates empty padding, setfill fills that padding with a specific character.

Syntax:
cout << setfill('.') << setw(20) << "Chapter 1";
Result: ...........Chapter 1

Why use it? It's essential for creating readable tables of contents, receipts, or aligning financial data.

Receipt Printer Simulator
cout << left << setfill('.') << setw(25) << "Coffee"; cout << "$4.50";
Coffee...................$4.50

5. String Handling & Math Functions

String Functions <cstring>

Manage character arrays and strings safely:

  • strlen(str): Returns the number of characters.
  • strncpy(dest, src, n): Copies n characters to prevent buffer overflow.
  • strcmp(s1, s2): Compares strings; returns 0 if they match.
Practical Code Snippet
char szSource[] = "Copy this!";
char szDest[50];
// Safely copy 49 chars (leaving room for null)
strncpy(szDest, szSource, 49);
szDest[49] = 0;
cout << "Length: " << strlen(szDest);
Copy this!
Length: 10

Specific String Class Functions

Useful Members
  • Concatenation (+)
    Joins strings together.
    string s = "Hello" + s2;
  • getline(cin, var)
    Reads a full line of text (including spaces).
    VS cin >> var which stops at the first space!
  • Modifiers
    str.erase(pos, len): Deletes chars.
    str.insert(pos, "text"): Adds chars at a position.
The "Space" Problem

Try typing "John Smith" below and see the difference.

Simulation Code: Waiting...
Memory Value: ?
Result explanation will appear here.

Module 4 Knowledge Check

Answer the following multiple-choice questions to test your understanding.

1. Which statement is used to display output in C++?

Explanation: cout (character output) is the standard object used with the insertion operator (<<) to print data to the console.

2. What does the escape sequence \n do?

Explanation:The \n character is a newline character that instructs the cursor to move to the beginning of the next line.

3. Which header file is required for formatted output functions?

Explanation: The iomanip header stands for "input-output manipulation" and is necessary for using functions like setprecision or setw.

4. What is the purpose of setprecision(2)?

Explanation: This manipulator is used to set the number of significant digits or decimal places (when used with fixed) displayed for floating-point numbers.

5. Which manipulator forces trailing zeros to be displayed?

Explanation: Even if a number is a whole number (like 5.00), showpoint ensures the decimal point and trailing zeros are shown in the output.