- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert a std::string to const char* or char* in C++?
In this section, we will see how to convert C++ string (std::string) to const char* or char*. These formats are C style strings. We have a function called c_str(). This will help us to do the task. It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
Following is the declaration for std::string::c_str.
const char* c_str() const;
This function returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object. If an exception is thrown, there are no changes in the string.
Example Code
#include <iostream> #include <cstring> #include <string> int main () { std::string str ("Please divide this sentence into parts"); char * cstr = new char [str.length()+1]; std::strcpy (cstr, str.c_str()); char * p = std::strtok (cstr," "); while (p!=0) { std::cout << p << '\n'; p = std::strtok(NULL," "); } delete[] cstr; return 0; }
Output
Please divide this sentence into parts
Advertisements