
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to convert an std::string to const char* or char* in C++?
You can use the c_str() method of the string class to get a const char* with the string contents.
example
#include<iostream> using namespace std; int main() { string x("hello"); const char* ccx = x.c_str(); cout << ccx; }
Output
This will give the output −
hello
To get a char*, use the copy function.
Example
#include<iostream> using namespace std; int main() { string x("hello"); // Allocate memory char* ccx = new char[s.length() + 1]; // Copy contents std::copy(s.begin(), s.end(), ccx) cout << ccx; }
Output
This will give the output −
hello
- Related Articles
- How to convert a std::string to const char* or char* in C++?
- Difference between const char* p, char * const p, and const char * const p in C
- How to convert string to char array in C++?
- Convert string to char array in Java
- Convert Char array to String in Java
- Convert string to char array in C++
- Java Program to convert Char array to String
- How to convert a single char into an int in C++
- How to convert char field to datetime field in MySQL?
- Copy char array to string in Java
- How do I convert a char to an int in C and C++?
- Append a single character to a string or char array in java?
- How to change a specific char in a MySQL string?
- Convert CHAR to HEX in SAP system and functions
- Swift Program to Convert Char type variables to Int

Advertisements