CodeBlanks Logo Icon CodeBlanks

Formatting

Learn formatting with stringstream.

Formatting with ostringstream

ostringstream enables number formatting with tools from the <iomanip> header. std::fixed and std::setprecision control the number of decimal places.

Example: oss << std::fixed << std::setprecision(2) << 3.14159;. This writes 3.14159 as "3.14". std::fixed sets fixed point notation and std::setprecision(2) sets two decimal places. std::hex gives hexadecimal, std::setw(n) sets field width. With these tools table and report output is formatted neatly.

Formatting tools

The <iomanip> header offers a rich set of formatting tools. std::fixed gives fixed point and std::scientific gives scientific notation.

std::setw(n) sets the field width of the next output to n; std::setfill('0') fills the space with zeros. Example: oss << std::setw(5) << std::setfill('0') << 42; gives "00042". std::hex sets hexadecimal and std::dec sets decimal base. These tools are used to align report and table output.

Practice Format pi to two decimals

The starting code has a pi variable of 3.14159. Create a std::ostringstream. Format pi with std::fixed and std::setprecision(2). Get the string with .str() and print it with std::cout.

Starter code

main.cpp
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>

int main() {
    double pi = 3.14159;
    // Format pi to two decimals and print

    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>

int main() {
    double pi = 3.14159;
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(2) << pi;
    std::cout << oss.str();
    return 0;
}

Expected output

3.14

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does std::setprecision(2) do?

main.cpp
oss << std::fixed << std::setprecision(2) << 3.14159;
  • Shows two integer digits
  • Shows two decimal places Correct answer
  • Sets field width to 2
  • Doubles the number

Explanation: setprecision(2) shows two decimal places.

2 Match each tool to its role

Term Meaning
std::fixed Fixed point
std::setprecision Decimal places
std::setw Field width
std::hex Hexadecimal base

3 Complete the setprecision call

Question
oss << std::fixed << std::____(2) << 3.14;
Answer
oss << std::fixed << std::setprecision(2) << 3.14;

Explanation: std::setprecision sets the number of decimal places.

All lessons in Intermediate