LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Predict the Output · Question 7

std::format alignment, width and precision Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <format>
#include <iostream>

int main() {
    std::cout << std::format("[{:6}][{:<6}][{:^6}][{:>6}]\n", 42, 42, 42, "ab");
    std::cout << std::format("[{:.2f}][{:08.3f}][{:+d}][{:#b}][{:X}]\n", 3.14159, 2.5, 7, 5, 255);
    std::cout << std::format("{1} {0} {1}\n", "a", "b");
    return 0;
}
  • A [ 42][42 ][ 42 ][ ab] [3.14][0002.500][+7][0b101][FF] b a b Correct
  • B [42 ][42 ][ 42 ][ab ] [3.14][0002.500][+7][0b101][FF] b a b
  • C [ 42][42 ][ 42 ][ ab] [3.14][2.500][7][101][ff] a b a
  • D [ 42][42 ][ 42 ][ ab] [3.14][0002.500][+7][0b101][FF] b a b
Correct Answer: Option A

Numbers align right by default and strings left; < ^ > override that. 08.3f pads with zeros to width 8, + forces a sign, # adds a prefix, and {1} {0} select arguments by position.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links