
- 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 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
- Related Articles
- How to convert an 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
- Append a single character to a string or char array in java?
- How to change a specific char in a MySQL string?
- How to convert char field to datetime field in MySQL?
- How to convert a single char into an int in C++
- Copy char array to string in Java
- Different methods to append a single character to a string or char array in Java
- Convert CHAR to HEX in SAP system and functions
- Swift Program to Convert Char type variables to Int

Advertisements