简体   繁体   English

printf() std::string_view 的正确方法?

[英]Correct way to printf() a std::string_view?

I am new to C++17 and to std::string_view .我是 C++17 和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?这是 printf() 的正确方法吗?

#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?) (或者将它与任何其他 printf 风格的函数一起使用?)

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 https://godbolt.org/z/nbeMWo1G1

As you can see you were close to solution.如您所见,您已接近解决方案。

You can use:您可以使用:

assert(sv.length() <= INT_MAX);
std::printf(
    "%.*s",
    static_cast<int>(sv.length()),
    sv.data());

The thing to remember about string_view is that it will never modify the underlying character array.关于string_view要记住的一点是它永远不会修改底层字符数组。 So, if you pass a C-string to the string_view constructor, the sv.data() method will always return the same C-string.因此,如果您将 C 字符串传递给string_view构造函数,则sv.data()方法将始终返回相同的C 字符串。

So, this specific case will always work:因此,这种特定情况将始终有效:

#include <string_view>
#include <cstdio>

int main() {
    std::string_view sv {"Hallo!"};
    printf("%s\n", sv.data());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM