Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to printf() a std::string_view?

I am new to C++17 and to std::string_view. I learned that they are not null terminated and must be handled with care.

Is this the right way to printf() one?

#include<string_view>
#include<cstdio>

int main()
{
    std::string_view sv{"Hallo!"};
    printf("=%*s=\n", static_cast<int>(sv.length()), sv.data());
    return 0;
}

(or use it with any other printf-style function?)

like image 297
kuga Avatar asked Dec 07 '25 09:12

kuga


2 Answers

This is strange requirement, but it is possible:

std::string_view s{"Hallo this is longer then needed!"};
auto sub = s.substr(0, 5);
printf("=%.*s=\n", static_cast<int>(sub.length()), sub.data());

https://godbolt.org/z/nbeMWo1G1

As you can see you were close to solution.

like image 51
Marek R Avatar answered Dec 08 '25 21:12

Marek R


You can use:

assert(sv.length() <= INT_MAX);
std::printf(
    "%.*s",
    static_cast<int>(sv.length()),
    sv.data());
like image 29
eerorika Avatar answered Dec 08 '25 22:12

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!