1

How would you convert a std::string_view to a null-terminated c string? I've passed a string_view into a function, and need to pass that into another function, which takes a const char* parameter. However, looking at this documentation for string_view, it says

data() may return a pointer to a buffer that is not null-terminated. Therefore it is typically a mistake to pass data() to a routine that takes just a const CharT* and expects a null-terminated string.

Is there a way to properly get a null-terminated c string from a string_view?

Jeffmagma
  • 452
  • 2
  • 8
  • 20
  • 1
    This is what has prompted some people to make a separate `zstring_view` class. If the string view isn't referring to a null-terminated string, any method to create one is going to be expensive relatively. – chris Jan 07 '18 at 03:23
  • 2
    `std::string s(view); f(s.c_str());` – Igor Tandetnik Jan 07 '18 at 03:24
  • You can try: string(stringViewObject).c_str() – Daniel Illescas Jan 07 '18 at 03:25
  • 1
    should I just start off with taking a `const string&` parameter instead? If I'm going to be constructing a string anyways? I know I'll always be passing a `std::string` or string literal to this function – Jeffmagma Jan 07 '18 at 03:25
  • 1
    @Jeffmagma: "*Is there a way to properly get a null-terminated c string from a `string_view`?*" If the answer to this question was "yes", `string_view::substr` would not be able to return a `string_view`. – Nicol Bolas Jan 07 '18 at 03:29

0 Answers0