C++ String c_str() Function

Overview
The c_str() function in C++ converts a string to an array of characters and terminates this array with a null character at the end. It is present in the "cstring" header of the C++ library, so to use the c_str() function, we must include the "cstring" header. The function does not accept any parameters. It returns a pointer to this array of characters.
Use of string c_str() Function
- The c_str() function in C++ converts a given string to an array of characters.
- After converting the string to an array of characters, it terminates the array with a null character at the end of the array.
Transform Your Career
Choose from our industry-leading programs designed for career success
Modern Software and AI Engineering Program
Master full-stack development with AI integration
+1000 moreModern Data Science and ML with specialisation in AI
Advanced data science techniques with AI specialization
+1000 moreAdvanced AIML with Specialisation in Agentic AI
Deep dive into AIML with focus on Agentic systems
+1000 moreDevOps, Cloud & AI Platform Engineering
Build and manage AI-powered cloud infrastructure
+1000 moreAI Engineering Advanced Certification by IIT-Roorkee
Premier AI engineering certification from IIT-Roorkee
Syntax of String c_str() in C++
Parameters of String c_str() in C++
The c_str() function in C++ does not accept any parameters.
Return Value of String c_str() in C++
The function returns a constant pointer to a string representing the string object's value.
Exceptions of String c_str() in C++
- If this function throws any exception, then there is no change in the original string.
Turn Learning into Career Growth
Example
Scaler Placement Report and Statistics
Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.
C++ Implementation
Output
How Does String c_str() in C++ work?
Here we will see another example of the c_str() function in C++, and with the explanation of the example, we will understand the working of the function.
C++ Implementetion
Output
Explanation
- In the first line, we have created a string named str and initialized it with the value "This is a string".
- In the second line, we have created an array of characters ch with a size of one more than the size of the string str. This is because the c_str() function will store one extra pointer, i.e., a null pointer at the end of the array.
- Then, we used the strcpy() function to copy the str value into the ch array.
- Then we just printed the values in the str and ch.
Conclusion
In this quick tutorial, we have discussed the c_str() function in C++, and we can conclude the article with the following points.
- The c_str() function in C++ converts a given string to an array of characters.
- The function does not accept any parameters and returns a pointer to the array of characters.