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.
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.
Example
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.