Search⌘ K
AI Features

Printing With printf()

Explore how to print std::string_view objects using printf by applying precision specifiers and type casting. Understand the formatting details needed to output non-owning string data correctly, improving your grasp of C++17 string handling techniques.

We'll cover the following...

For example:

C++ 17
#include <iostream>
using namespace std;
int main() {
std::string s = "Hello World";
std::string_view sv = s;
std::string_view sv2 = sv.substr(0, 5);
printf("My String %s", sv2.data()); // oops?
}

Instead you should use:

printf("%.*s\n", static_cast<int>(sv2.size()),
...