String Views

string_view to C-style string

How do I convert a std::string_view to a C-style string safely?

Abstract art representing computer programming

To convert a std::string_view to a C-style string safely, you need to ensure the resulting C-style string is null-terminated.

While std::string_view provides a data() method to access the underlying character array, this array may not be null-terminated.

The safest approach is to create a std::string from the std::string_view and then use the c_str() method. Here's an example:

#include <iostream>
#include <string>
#include <string_view>

void printCString(const char* cstr) {
  std::cout << cstr << '\n';
}

int main() {
  std::string_view view{"Hello, world"};

  // Convert std::string_view to std::string,
  // then to C-style string
  std::string str{view};
  const char* cstr = str.c_str();  

  printCString(cstr);
}
Hello, world

Direct Use of data()

If you are certain that the std::string_view references a null-terminated string, you can use data() directly, but this approach is risky and not recommended for general use:

#include <iostream>
#include <string_view>

void printCString(const char* cstr) {
  std::cout << cstr << '\n';
}

int main() {
  std::string_view view{"Hello, world"};
  printCString(view.data());  
}
Hello, world

Ensuring Null-Termination

For cases where you need to ensure null-termination, using std::string is the safest method. Alternatively, you can manually create a null-terminated string if performance is critical and you know the string length:

#include <iostream>
#include <string>
#include <string_view>
#include <vector>

void printCString(const char* cstr) {
  std::cout << cstr << '\n';
}

int main() {
  std::string_view view{"Hello, world"};
  std::vector<char> buffer(
    view.begin(), view.end()
  );
  buffer.push_back('\0');  
  const char* cstr = buffer.data();

  printCString(cstr);
}
Hello, world

In summary, converting std::string_view to a C-style string safely typically involves creating a std::string and using its c_str() method to ensure null-termination.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved