Skip to content

Latest commit

 

History

History
219 lines (143 loc) · 2.79 KB

File metadata and controls

219 lines (143 loc) · 2.79 KB

std::format is a new way to format text which

  • separates formatting from outputting
  • is more type-safe
  • allows reordering
C++17 C++20
std::printf("%d baskets of %s", n, desc);

//OR

std::cout << n << " baskets of " << desc;
 
std::cout << std::format("{} baskets of {}", n, desc);
 

Ordering

whoops! Apples! 5 baskets left
std::printf("%s! %d baskets left", n, desc);
 
std::cout <<
   std::format("{1}! {0} baskets left", n, desc);
 

Formatting

Detailed formatting is similar to printf, but actually based on Python!

The general form is

fill-and-align sign # 0 width precision L type

(with each part optional).

format result
std::string s;

// fill-and-align

s = std::format("{:6}",   123); //default
s = std::format("{:<6}",  123); //left
s = std::format("{:^6}",  123); //center
s = std::format("{:>6}",  123); //right

s = std::format("{:6}",  "abc"); //default
s = std::format("{:<6}", "abc"); //left
s = std::format("{:^6}", "abc"); //center
s = std::format("{:>6}", "abc"); //right

s = std::format("{:$^6}", "abc"); //fill with

// sign

s = std::format("{}",    123); //default
s = std::format("{}",   -123); //default

s = std::format("{:-}",  123); //same as def
s = std::format("{:-}", -123); //same as def

s = std::format("{:+}",  123); //always sign
s = std::format("{:+}", -123); //always sign

s = std::format("{: }",  123); //space if pos
s = std::format("{: }", -123); //space if pos

// results...

// fill-and-align

assert(s == "   123"); // numbers >
assert(s == "123   ");
assert(s == " 123  "); // slightly <
assert(s == "   123");

assert(s == "abc   "); // strings <
assert(s == "abc   ");
assert(s == " abc  "); // slightly <
assert(s == "   abc");

assert(s == "$abc$$"); // fill with $

// sign

/* {} */ assert(s == "123");
/* {} */ assert(s == "-123");

/*{:-}*/ assert(s == "123");
/*{:-}*/ assert(s == "-123");

/*{:+}*/ assert(s == "+123");
/*{:+}*/ assert(s == "-123");

/*{: }*/ assert(s == " 123");
/*{: }*/ assert(s == "-123");


Chrono

C++17 C++20
???

 
std::cout << std::format("The time is {}", std::system_clock::now());