Assign or construct a std::string from a C string
To convert a C string to a std::string, assign it to a string variable or pass it to the constructor. Either way you get a std::string that holds a copy of the characters up to the terminating null character.
#include <iostream>
#include <string>
int main() {
const char* c_string = "Hello, C++";
std::string text = c_string; // copies the characters
text += "!";
std::cout << text << '\n'; // Hello, C++!
std::cout << text.length() << '\n'; // 11
}
What a C string is
A C string is a run of char values that ends with a null character, written '\0'. It is usually held in a char array or a const char* pointer. The literal "Hello" takes six bytes in memory: five letters plus the terminator, so sizeof("Hello") is 6. The older type is covered in what is a C string.
The terminator is how C functions find the end of the text. A std::string keeps track of its own length, so it does not depend on the terminator to know where it ends.
Ways to convert
- Construction:
std::string text(c_string); - Initialization with
=:std::string text = c_string;does the same thing as construction. - Assignment to an existing string:
text = c_string;replaces whatevertextheld before. - Partial copy:
std::string text(c_string, 5);copies only the first five characters.
Character arrays work the same way, because the array decays to a pointer:
char name[] = "Ada";
std::string text = name; // text holds "Ada"
Null pointers are not empty strings
An empty C string points to a single null character. A null pointer points to nothing at all, and passing one to the std::string constructor is undefined behavior. Check the pointer first:
const char* maybe_text = nullptr;
std::string text = maybe_text ? maybe_text : "";
Get a C string back from std::string
Use c_str() to get a const char* from a std::string:
std::string text = "Hello";
const char* raw = text.c_str();
The pointer stays valid only while text exists and is not changed. If an older function needs the text for longer, copy it instead of keeping the pointer.
If the text holds digits
If the text comes from the keyboard, you may not need a C string at all, and how to read string input in C++ shows how to read straight into a std::string. If the text holds digits and you need a number, see how to convert a string to an int in C++.