
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert 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
Advertisements